【发布时间】:2016-08-02 19:58:03
【问题描述】:
我正在制作我的第一个 C++ 项目。这是一个简单的温度转换器。
我用 if 语句制作了一个测试部分 [代码 1]。 if 语句将比较用户输入。例如,如果您用户键入 c,然后键入 k(Celsius-Kelvin)。它应该运行函数[code 2] CtoK();但我没有运行所有功能为什么要这样做?
它尝试使用 return 但我没有(它也没有给出错误,所以我保留了它)
如果你们看到别的东西请说Code on pastebin
也想牢记: 刚说要学C++ 不是英语母语,所以如果有拼写和语法错误,请说出来,以便我学习它
[代码 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();
}
}
}
[代码 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;
}
【问题讨论】:
-
firstDegrees == 'C' || 'c'- 比较不是这样工作的......可能你想要firstDegrees == 'C' || firstDegrees == 'c' -
1) 如果你有超过 1 个相关的
if,你应该有else if和else。 2)if (firstDegrees == 'C' || 'c')我相信总是评估为真 -
我在 Python 中多次看到这个错误,但对于 C++ 来说这是第一次。
-
@MarkRansom 信不信由你,这也是 c++ 中的常见错误。
-
唉,在可能的 数百个 重复项中找到一个是近乎徒劳的效率练习,因为问题标题和文本通常如此模糊,几乎没有共同点锁定到。我想,对语言入门的引用是一个不错的后备方案。
标签: c++ visual-studio