How to diplay with decimals?

Hello,

I am trying to make the code below display the result with decimals. I tried using setprecision, but I am not too sure where to put it. I placed it in cout section where the answer is but it still doesn't come out correctly. Any feedback would be great.

Thanks in advance!

#include <iostream>
using namespace std;
//*Delcare function prototype*
int ConvertToCentimeters (double, double );
//declare exception class*
class NegativeNumber
{};
int main ( )
{
double inch = 0;
double cent = 0;
double answer;
char ContinuationFlag = 'Y';
while (toupper(ContinuationFlag) == 'Y')
{
cout << "Enter Inches for conversion : " << endl;
cin >> inch;
try
{
answer = ConvertToCentimeters ( inch, cent);
cout << "The conversion to centimeters is: " << answer << endl;
}
catch ( NegativeNumber )
{
cout << "Inches cannot be negative!" << endl;
}
cout << "Do you wish to enter any more numbers?" << endl;
cout << "Enter 'Y' or 'N'" << endl;
cin >> ContinuationFlag;
}
return 0;
}
int ConvertToCentimeters(double InputInch, double InputCent )
{
if ( InputInch < 0 )
{
throw NegativeNumber();
}
return (InputInch * 2.54 );
}
use it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>   // for setprecision

int main()
{
	
	double piApprox = 22.0 / 7.0;

	std::cout << "No precision: " << piApprox << std::endl;
	std::cout << std::setprecision(3) << "With precision: " << piApprox << std::endl;

	return 0;
}
thanks for the help. Still no luck. I was able to get it to show 2.00 but i need to show 2.54 which is what 1 * 2.54 is.

try
{
answer = ConvertToCentimeters ( inch, cent);
cout << "The conversion to centimeters is: " << setprecision(2) << fixed << answer << endl;
The issue is here.
1
2
3
4
5
6
7
8
int ConvertToCentimeters(double InputInch, double InputCent )
{
if ( InputInch < 0 )
{
throw NegativeNumber();
}
return (InputInch * 2.54 );
}


Your function is of type int

Integers always get rounded down to the nearest whole number, so instead of returning 2.54, it is returning 2

Change the function type to float or double and problem solved.

Also, don't forget to change the prototype from int to float or double.
It worked. Thanks guys. I could of sworn I tried that already.
Topic archived. No new replies allowed.