我的fahrenheit-celcius程序会忽略我的if-else语句,并在每次运行该程序时将值更改为0

My fahrenheit-celcius program ignores my if-else statement and changes value to 0 everytime I run the program

本文关键字:我的 程序 运行 fahrenheit-celcius if-else 语句      更新时间:2023-10-16

我的if-else语句似乎不起作用,有人有什么想法吗?

所以我用C++创建了这个简单的华氏摄氏度转换控制台应用程序。该程序使用一个简单的if-else语句来确定他们想要的转换,华氏摄氏度还是华氏摄氏度。

然而,该代码目前不起作用,它会立即转换华氏摄氏度,并完全忽略我用来获取用户输入的std::cin。相反,每次我运行程序时,他们都会输入0的值。

#include<iostream>
using namespace std;
int main() {
unsigned short int fahrenheit{}, celsius{};
char unit;
cout << "Choose what unit you want to start with" << endl;
cin >> unit;
if (unit == 'c') {
cout << "Enter the temperature in Celsius : " << endl;
cin >> celsius;
fahrenheit = (celsius * 9.0) / 5.0 + 32;
cout << "The temperature in Fahrenheit : " << fahrenheit << endl;
} else {
cout << "Enter the temperature in Fahrenheit : " << endl;
cin >> fahrenheit;
fahrenheit = (celsius * 9.0) / 5.0 + 32;
cout << "The temperature in Celcius : " << celsius << endl;
}
std::cin.clear(); // reset any error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); // ignore any characters in the input buffer until we find an enter character
std::cin.get(); // get one more char from the user
return 0;
}

在if条件中,使用unit=='C' || unit=='c'。可能是您输入了大写字母。对于负值去除unsign,对于浮动答案转换int to double。在其他条件fahrenheit = (celsius * 9.0) / 5.0 + 32;错误的情况下,它将是celsius = ( fahrenheit - 32) * 5.0 / 9.0。。

在else块中,您有notcelsius设置值
我想你想做这样的事情:

celsius = (fahrenheit - 32) * 5 / 9.0;

但是,你的代码是

fahrenheit = (celsius * 9.0) / 5.0 + 32;
相关文章: