【发布时间】:2018-03-16 12:23:02
【问题描述】:
每次我运行此代码时,无论出于何种原因,它都会调用所有函数,无论 if 语句的计算结果是否为 true
int main()
{
char StartUnit, EndUnit;
double StartVal = 0, EndVal = 0;
double CalcVal = 0;
static double result = 0;
//Receive user input
cout << "Please enter the unit which you would like to convert from: ";
cin >> StartUnit;
cout << "What is your initial value?: ";
cin >> StartVal;
cout << "Please enter the unit which you would like to convert to: ";
cin >> EndUnit;
//Step 1: Convert input to celsius
if (StartUnit = 'f')
{
CalcVal = FarCel(StartVal);
}
if (StartUnit = 'k')
{
CalcVal = KelCel(StartVal);
}
if (StartUnit = 'r')
{
CalcVal = RakCel(StartVal);
}
//Step 2: Conver celsius to desired value
cout << CalcVal;
return 0;
}
当我输出CalcVal时,无论如何,它似乎贯穿了所有三个函数。不管我输入什么,r、c、f,它们的评价都是一样的。我可以就我哪里出错了提供一些建议吗?
已解决:问题的答案是==用于比较,我的if测试使用=
【问题讨论】:
-
如果您的教授不能立即发现明显的错误并给出解释,正如您所说,您真的需要找一位新教授。你得到的那个是完全无能的。
-
把你的编译器的警告级别调高到足够高,它很有可能会因为 ==/= 混淆而向你发出血腥的蓝色谋杀。 Visual Studio 中的第 4 级并将 -Wall -Wextra 添加到 g++ 命令行应该可以完成这项工作。
-
这个问题有答案,请选择一个作为接受答案。
-
@SamVarshavchik 这值得商榷。另一方面,编译器应该绝对警告这一点。
标签: c++ function if-statement char comparison