I'm learning C and am supposed to make a program which takes height in inches, weight in pounds, and age from the user, and gives them the size of their clothing. You get the size of their hat by dividing their weight by their height and multiplying that result with 2.9. I have been testing my code and the output is correct but always has an extra 1 (like 9.941 instead of 9.94) at the end. My answer should only have two digits after the decimal point, even if it's a zero. Does anyone have any tips? Thanks guys. Here is my code:
#include<iostream>
#include<iomanip>
using namespace std;
void HatSize(double userHeight, double userWeight) {
cout << setprecision(2) << fixed << ((userWeight / userHeight) * 2.9);
}
int main(){
double height;
double weight;
double age;
cout << "Give me your height in inches, weight in pounds, and age in years. I will give you your hat size, jacket size (inches at chest)\nand waist size in inches." << endl;
cin >> height;
cin >> weight;
cin >> age;
HatSize(height, weight);
cout << HatSize;
return 0;
}
CodePudding user response:
You're using setprecision
correctly, the issue is that you have an additional statement that is generating the 1
.
Remove the cout << HatSize;
line. HatSize
is a function that returns void, so you're sending the actual function itself as input to cout
, which is being interpreted as 1
.
I would also recommend adding a << endl
to the cout
in your HatSize
function, so that your output finishes with a newline.
void HatSize(double userHeight, double userWeight) {
cout << setprecision(2) << fixed << ((userWeight / userHeight) * 2.9)
<< endl; // Newline to make output nicer
}
int main(){
double height;
double weight;
double age;
cout << "Give me your height in inches, weight in pounds, and age in years. I will give you your hat size, jacket size (inches at chest)\nand waist size in inches." << endl;
cin >> height;
cin >> weight;
cin >> age;
HatSize(height, weight);
// cout << HatSize !!!!!!!!! Get rid of this
return 0;
}