为什么这些函数会截断 return 值?
Why do these functions truncate the return value?
注意下面有作业
编辑:
去掉无用的信息
很明显,这是一项家庭作业,除了我函数中的计算之外,一切似乎都是正确的。
如何 return 非截断值?
float hat(float weight, float height) {
return (weight/height)*2.9;
}
float jacket(float weight, float height, int age) {
double result = (height * weight) / 288;
/*now for every 10 years past 30 add (1/8) to the result*/
if((age - 30) > 0){
int temp = (age - 30) / 10;
result = result + (temp * .125);
//cout<<"result is: "<<result<<endl;
}
return result;
}
float waist(float weight, int age) {
double result = weight / 5.7;
/*now for every 2 years past 28 we add (1/10) to the result*/
if((age - 28) > 0){
int temp = (age - 28) / 2;
result = result + (temp * .1);
}
return result;}
设置fixed
:
// Output data //
cout << fixed;
cout << "hat size: " << setprecision(2) << hat(weight, height) << endl;
cout << "jacket size: " << setprecision(2) << jacket(weight, height, age) << endl;
cout << "waist size: " << setprecision(2) << waist(weight, age) << endl;
cout << "hat size: " << setprecision(2) << hat(weight, height) << endl;
您在 iostream 格式化输出的工作方式中遇到了陷阱。
在格式化浮点值的"default"模式中(没有请求fixed
或scientific
输出),精度是总 要打印的位数,小数点两边。认为 "significant figures",而不是 "number of fractional digits"。
对于您要执行的操作,我建议您使用 "fixed" 模式或手动舍入,然后不要指定精度。
注意下面有作业
编辑:
去掉无用的信息
很明显,这是一项家庭作业,除了我函数中的计算之外,一切似乎都是正确的。
如何 return 非截断值?
float hat(float weight, float height) {
return (weight/height)*2.9;
}
float jacket(float weight, float height, int age) {
double result = (height * weight) / 288;
/*now for every 10 years past 30 add (1/8) to the result*/
if((age - 30) > 0){
int temp = (age - 30) / 10;
result = result + (temp * .125);
//cout<<"result is: "<<result<<endl;
}
return result;
}
float waist(float weight, int age) {
double result = weight / 5.7;
/*now for every 2 years past 28 we add (1/10) to the result*/
if((age - 28) > 0){
int temp = (age - 28) / 2;
result = result + (temp * .1);
}
return result;}
设置fixed
:
// Output data //
cout << fixed;
cout << "hat size: " << setprecision(2) << hat(weight, height) << endl;
cout << "jacket size: " << setprecision(2) << jacket(weight, height, age) << endl;
cout << "waist size: " << setprecision(2) << waist(weight, age) << endl;
cout << "hat size: " << setprecision(2) << hat(weight, height) << endl;
您在 iostream 格式化输出的工作方式中遇到了陷阱。
在格式化浮点值的"default"模式中(没有请求fixed
或scientific
输出),精度是总 要打印的位数,小数点两边。认为 "significant figures",而不是 "number of fractional digits"。
对于您要执行的操作,我建议您使用 "fixed" 模式或手动舍入,然后不要指定精度。