gpt4 book ai didi

c++ - 在 C++ 中意外移动了小数点

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:59:33 24 4
gpt4 key购买 nike

这是我在 stackoverflow 上的第一篇文章。我目前正在重新学习 C++,我无法理解在该系统中变量 double userBase[j].height 的意外更改值过程中发生了什么。

正如您在第一张照片中所见,一切似乎都运行良好: enter image description here

现在,每次我想从 5 结构数组中打印出所有收集信息的表格时,高度值突然改变并且移动了 2 个小数点。 enter image description here

我目前正在找出问题出在哪里。我怀疑它来自 setprecision() 但我不知道它是如何发生的。

我的源代码:

#include <iostream>    
#include <iomanip>
#include <windows.h>

using namespace std;

const int size = 5;

struct users{

double height, ft, in, weight, age;
double bmi;
int bmiLevel;
string gender;
};

int main(){


users userBase[size];

for(int i = 0; i<size; i++){

cout << "Enter your weight (lbs): ";
cin >> userBase[i].weight;
userBase[i].weight = userBase[i].weight*0.453592;


cout << "Enter your height (feet): ";
cin >> userBase[i].ft;
cout << "Enter your height (inches): ";
cin >> userBase[i].in;
userBase[i].ft = userBase[i].ft * 30.48;
userBase[i].in = userBase[i].in * 2.54;
userBase[i].height = userBase[i].ft + userBase[i].in;

cout << "\n\n\nheight and weight are converted to kilograms and centimeters respectively \n\n";

cout << "Weight: " << userBase[i].weight << " kg" << endl;
cout << "Height: " << userBase[i].height << " cm" << endl;

userBase[i].height = userBase[i].height * 0.01;
userBase[i].bmi = userBase[i].weight / (userBase[i].height*userBase[i].height);
cout << "Your Body Mass Index (BMI): " << userBase[i].bmi << endl;

if(userBase[i].bmi<18){
cout << "Underweight! ";
}
if(userBase[i].bmi>18 && userBase[i].bmi<25){
cout << "Ideal";
}
if(userBase[i].bmi>25 && userBase[i].bmi<30){
cout << "Overweight";
}
if(userBase[i].bmi>30){
cout <<"Obese";
}
system("CLS");
}


cout<<left<<fixed<<setprecision(2);
cout<<"Weight Height BMI Status \n";
for(int j = 0; j < size; j++){

cout<<setw(0)<<userBase[j].weight
<<setw(10)<<"kg"
<<setw(0)<<userBase[j].height
<<setw(10)<<"cm"
<<setw(10)<<userBase[j].bmi;

if(userBase[j].bmi<18){
cout << "Underweight! ";
}
if(userBase[j].bmi>18 && userBase[j].bmi<25){
cout << "Ideal";
}
if(userBase[j].bmi>25 && userBase[j].bmi<30){
cout << "Overweight";
}
if(userBase[j].bmi>30){
cout <<"Obese";
}
cout << endl;
}
}

我已经花了大约一个小时来弄清楚这个问题,非常感谢对这篇文章的任何帮助!

最佳答案

我发现问题出在哪里:

在代码的中间,我将所有高度的值乘以 0.01,这使得它在打印表格时移动了两位小数。

我的解决方案是将它乘回 100 以获得以厘米为单位的原始高度。

谢谢@someprogrammerdude 的建议!

关于c++ - 在 C++ 中意外移动了小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48923051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com