我正在制作我的第一个项目c ++。这是一个简单的温度转换器。
我用if语句做了一个测试部分[代码1]。 if语句将比较用户输入。例如,如果您使用键入c然后键入k(Celsius-Kelvin)。它应该运行函数[code 2] CtoK();但我不是它运行所有功能为什么会这样做?
它尝试使用return但我没有(它也没有出错,所以我保留了它)
如果你们看到其他人请说Code on pastebin
也认为要记住: 刚刚学会了学习C ++ 不是母语,所以如果有拼写和语法错误,请说出来,以便我可以从中学习
[code 1]
void whatToWhat(char firstDegrees, char secondDegrees) {
if (firstDegrees == 'C' || 'c') {// tests if the user want form c to f
if (secondDegrees == 'F' || 'f') {
CtoF();
}
}if (firstDegrees == 'C' || 'c') {// tests if the user want form c to k
if (secondDegrees == 'K' || 'k') {
CtoK();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to c
if (secondDegrees == 'C' || 'c') {
FtoC();
}
}if (firstDegrees == 'F' || 'f') {// tests if the user want form f to k
if (secondDegrees == 'K' || 'k') {
FtoK();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to f
if (secondDegrees == 'F' || 'f') {
KtoF();
}
}if (firstDegrees == 'K' || 'k') {// tests if the user want form k to c
if (secondDegrees == 'C' || 'c') {
KtoC();
}
}
}
[code 2]
void CtoF() {// c to f furmula
double input;
cout << "Enter a number[Celsius-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << input * 1.8 + 32 << " Fahrenheit " << endl;
return;
}
void CtoK() {// c to k furmula
double input;
cout << "Enter a number[Celsius-Kelvin]" << endl;
cin >> input;
cout << "it's " << input + 273.15 << " Kelvin " << endl;
return;
}
void FtoC() {//f to c furmula
double input;
cout << "Enter a number[Fahrenheit-Celsius]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 << " Celsius " << endl;
}
void FtoK() {//f to k furmula
double input;
cout << "Enter a number[Fahrenheit-Kelvin]" << endl;
cin >> input;
cout << "it's " << input / 1.8 - 32 + 273.15 << " Kelvin " << endl;
return;
}
void KtoF() {// k to f furmula
double input;
cout << "Enter a number[Kelvin-Fahrenheit]" << endl;
cin >> input;
cout << "it's " << (input - 273.15) * 1.8 + 32 << " Fahrenheit " << endl;
}
void KtoC() {// k to c furmula
double input;
cout << "Enter a number[Kelvin-Celsius]" << endl;
cin >> input;
cout << "it's " <<273.15 - input << " Celsius " << endl;
return;
}
答案 0 :(得分:1)
if(firstDegrees == 'K' || 'k')
将始终评估为 true ,因为k
因为是Not Null
,意味着有效,表示 True 。
您需要以与此类似的方式编写所有表达式:(firstDegrees == 'K' || firstDegrees == 'k')
此外,您希望在每个else
之后添加if
s,以获得更好,更清晰的逻辑控制。