【发布时间】:2022-08-18 15:32:01
【问题描述】:
我正在为这段代码苦苦挣扎。已经在这些 if、else if、else 语句上工作了几个小时。
void metric()
double mWeight;
double mHeight;
double mAge;
char mExercise;
bool mCorrectExercise = true;
int metricResult;
cout << \"Please type in your age: \";
cin >> mAge;
cout << \"Please type in your weight: \";
cin >> mWeight;
cout << \"Please type in your height: \";
cin >> mHeight;
cout << \"Finally, please select an exercise program that most closely matches yours.\\n\\n1) No exercise.\\n\\n2) 1-2 hours a week.\\n\\n3) 3-5hours a week.\\n\\n4) 6-10 hours a week\\n\\n5) 11-20 hours a week.\\n\\n6) 20+ hours a week.\\n\\n\";
cin >> mExercise;
if (mExercise == 1)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult << \"\\n\\n\";
}
else if (mExercise == 2)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.1 << \"\\n\\n\";
}
else if (mExercise == 3)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.25 << \"\\n\\n\";
}
else if (mExercise == 4)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.35 << \"\\n\\n\";
}
else if (mExercise == 5)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.5 << \"\\n\\n\";
}
else if (mExercise == 6)
{
metricResult = (mWeight * 11) + (mHeight * 8) - (mAge * 6.5) + 66;
cout << metricResult * 1.7 << \"\\n\\n\";
}
else
{
cout << \"Invalid input. Please try again.\\n\\n\";
}
}
他们没有成功打印 cout 结果。当语句中的数学公式曾经不同时,我早些时候让它有点工作。我试图让所有这些都像我很确定的陈述不是它应该是的那样。我还有一个问题,尽管输入了任何其他选项,但它只会打印选项 #1 的结果。
TLDR,使用当前代码,无论我从 1 到 6 选择哪个选项,它都不会打印。
谢谢
-
char mExercise是结果不等于 1-6 的原因。字符 \'1\' 的 ASCII 值是 49,例如,不是 (int) 1。也许您想改用int mExercise。 -
mExercise的类型为char。当输入为1时,从std::cin读取的mExercise的值为\'1\'(注意单引号),但值为\'1\'的char没有数值1.要修复,(1)将mExercise的类型更改为int(因此读取1的输入将进行转换,并给出1的数值而不是char的值@ 987654338@) 或 (2) 将if语句中的比较更改为mExercise == \'1\'(对于其他值也是如此)。
标签: c++