gpt4 book ai didi

C++ Cin 未正确执行

转载 作者:行者123 更新时间:2023-11-28 06:41:46 24 4
gpt4 key购买 nike

我在正确执行“cin >> calories”时遇到问题。代码会自动将 calories = 设置为 -279846518796,有时还会设置其他数字(通常是像以前一样的大负数)。从而使最终结果一团糟。即使我将“卡路里”设置为 int,我也会得到同样的错误。

#include <iostream>

int main( )
{
int height, weight, age, edible_newfoods;
double bmr, calories;
char gender, activity_level, newfood;

//Take user inputs.
cout << "Please provide your information." << endl;
cout << "male or female (m or f): ";
cin >> gender;
cout << "age in years: ";
cin >> age;
cout << "weight in pounds: ";
cin >> weight;
cout << "height in inches: ";
cin >> height;

//Ask the user how active they are, to get an input between four choices
cout << endl << "How active are you?" << endl;
cout << " s - sedentary" << endl;
cout << " c - casual exerciser--exercise ocasionally" << endl;
cout << " a - active exerciser--exercise 3-4 days a week" << endl;
cout << " d - devoted exerciser--exercise everyday" << endl;

//Take users activity level as a char
cout << "Enter the level of association with your activity level: ";
cin >> activity_level;

//Adding more food
cout << endl << "What type of food do you want to eat?" << endl;

cout << "Please use _ between words to create a single word. ";
cin >> newfood;

cout << "How many calories per item? ";
//This is where the cin automatically makes calories a giant negative number.
// causing the final output of results to be a mess.
cin >> calories;

//Calculations - Adjusting BMR to accommodate for activity level
switch (activity_level)
{
case 's':
case 'S': activity_level = 0.95; break;
case 'c':
case 'C': activity_level = 1.30; break;
case 'a':
case 'A': activity_level = 1.40; break;
case 'd':
case 'D': activity_level = 1.50; break;
}

if (age <= 65 && (gender == 'm' || gender == 'M')) {
bmr = 1.375 * ((66 + 6.3 * weight) + (12.9 * height) - (6.8 * age));
}
else {
bmr = 1.375 * ((655 + 4.3 * weight) + (4.7 * height) - (4.7 * age));
}

bmr = bmr * activity_level;

edible_newfoods = bmr / calories;

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(0);

//output the results to user.
cout << endl << "The BMR for a " << weight << " pound " << gender << " who is " << age << " years old is " << bmr
<< " calories number of " << newfood << " eaten = " << edible_newfoods;
}

请客气,我是 stackoverflow 和编码的新手。任何帮助,将不胜感激。谢谢

最佳答案

activity_levelchar 类型,将 double 分配给它看起来不正确:

char gender, activity_level, newfood;
...
activity_level = 0.95;

虽然它仍然是一种有效的语言结构,但它会导致 float 部分被截断并将 0 分配给 activity_level。请参阅 @KeithThompson 的评论。

好像需要两个不同的变量,

  • 一个 (char) 用于保留输入并在 switch 中使用,并且
  • 另一个(double)作为bmr = bmr * activity_level;的因子

关于C++ Cin 未正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838985/

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