c++ - 为什么这些函数会截断返回值?

标签 c++ function arithmetic-expressions truncated

注意下面有家庭作业。

编辑:

去掉无用的信息。

很明显,这是一项家庭作业,除了我函数中的计算之外,一切似乎都是正确的。

如何返回非截断值?

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;}

最佳答案

cout << "hat size: " << setprecision(2) << hat(weight, height) << endl;

您在 iostream 格式化输出的工作方式中遇到了陷阱。

在格式化浮点值的“默认”模式下(没有请求fixedscientific 输出),精度是总计要打印的位数,在小数点的两边。考虑“有效数字”,而不是“小数位数”。

对于您要尝试做的事情,我建议您使用“固定”模式或手动舍入,然后不要指定精度。

关于c++ - 为什么这些函数会截断返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062399/

相关文章:

c++ - 字符串替换和奇怪的字符

c - 将数组传递给函数的语法

c - C程序输出错误

c - 为什么这些括号在C语言中给出不同的答案?

c++ - 每次调用变量时如何生成随机数?

c++ - tellg() 函数给出错误的文件大小?

c++ - OpenGL - 无法读取/写入 2D 深度纹理数组

在函数中调用文件中的变量

python - 这个简单的 Python 分数加法器并不完全健壮,并且会收到错误。如何改进?

Prolog动态算术表达式