【发布时间】:2020-10-17 23:27:34
【问题描述】:
我试图制作一个转换器,用户将首先写入温度,然后选择他们想要转换的测量值。 如果我写一个数字,计算机会跳过 if 和 else if 语句,它会显示“错误选择”并再次循环。 我希望它在 if 语句中使用函数并再次循环,直到用户提示“q”或“Q”。 提前谢谢你。
我的代码如下:
#include <iostream>
#include <cmath>
#include <string>
#include <cstdlib>
using namespace std;
double fahrenheit_temperature {};
double fahrenheit_to_celsius (double fahrenheit_temperature);
double fahrenheit_to_kelvin (double fahrenheit_temperature);
double fahrenheit_to_celsius (double temperature)
{
cout << fahrenheit_temperature << " in fahrenheit is: ";
return round((5.0/9.0)*(fahrenheit_temperature - 32));
cout << endl;
}
double fahrenheit_to_kelvin (double temperature)
{
cout << fahrenheit_temperature << " in fahrenheit is: ";
return round((5.0/9.0)*(fahrenheit_temperature - 32) + 273);
cout << endl;
}
int main()
{
char selection {};
while ((selection != 'q') || (selection != 'Q'))
{
cout << "Enter temperature in fahrenheit: ";
if (!(cin >> fahrenheit_temperature))
{
cerr << "This is not a number!";
exit(0);
}
else
{
cout << "\nConvert to Celcius (write C or c) or Kelvin (write K or k)?";
cout << "\nIf you want to quit write q or Q" << endl;
if ((selection == 'C') || (selection == 'c'))
{
fahrenheit_to_celsius(fahrenheit_temperature);
}
else if ((selection == 'K') || (selection == 'k'))
{
fahrenheit_to_kelvin(fahrenheit_temperature);
}
else if ((selection == 'Q') || (selection == 'q'))
{
cout << "Thank you for using our superduper converter.";
break;
}
else
cout << "Wrong selection" << endl;
}
}
cout << "Thank you for using our superduper converter.";
return 0;
}
【问题讨论】:
-
您在代码中的哪个位置读入
selection? -
这种类型的问题意味着您没有使用调试器单步执行代码。如果您有一个调试器并且知道如何使用它(逐行逐行查看每个步骤的变量),您会在更短的时间内看到该错误,那么您需要发布这个问题。我这样说是为了敦促您花一些时间学习使用调试器。作为一名专业开发人员,我几乎每天都在使用它。
-
为什么人们一直声称 C++ 随机“跳过”语句?您可以排除这种情况,而是专注于自己的逻辑。
-
请参阅
std::toupper和std::tolower,因此您可以将输入转换为单个大小写并仅进行一次比较。
标签: c++ converters