简体   繁体   English

使用 BMI 计算器对 C++ 中的数字进行四舍五入

[英]Problem rounding numbers in C++ with a BMI calculator

I', trying to make a simple BMI calculator using C++.我',尝试使用 C++ 制作一个简单的 BMI 计算器。 When I input my personal height and weight, I get the correct result but I can't round the number to the nearest whole number.当我输入我的个人身高和体重时,我得到了正确的结果,但我无法将数字四舍五入到最接近的整数。 I looked up some videos and some articles and many of them suggested using the "round()" function.我查阅了一些视频和一些文章,其中许多建议使用“round()”function。 I tried that and the result I got was 0. All feedback helps.我试过了,我得到的结果是 0。所有反馈都有帮助。 Thanks!谢谢!

#include <iostream>
#include <cmath>

using namespace std;

float Calculate(float kilo, float centimeter)
{
    float meter = centimeter * 100;
    return kilo / (meter * meter);
}


int main()
{
    float kilo, centimeter;
    float bmi;

    cout << "BMI calculator." << endl;
    cout << "Please enter your weight in kilograms. ";
    cin >> kilo;
    cout <<"Please enter your height in centimeters. ";
    cin >> centimeter;

    bmi = Calculate(kilo, centimeter);

    cout << round(bmi) << endl;
    return 0;
}

Your formula for calculating BMI is wrong just change the line float meter = centimeter/100;您计算 BMI 的公式是错误的,只需更改线float meter = centimeter/100; . . because according to your formula any number multiplied by 100 and then squared becomes so big that you get very small floating point number after the division with weight that is eventually rounded that's why you always get 0 in output.因为根据您的公式,任何数字乘以 100 然后平方变得如此之大,以至于在除以最终四舍五入的权重后得到非常小的浮点数,这就是为什么在 output 中总是得到0的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM