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

C++ 我的华氏celcius程序忽略我的if-else语句,并在每次运行该程序时将值更改为0,c++,if-statement,C++,If Statement,我的if-else语句似乎不起作用,有人有什么想法吗 所以我用C++创建了一个简单的华氏转换程序控制台应用程序。该程序使用一个简单的if-else语句来确定他们想要的转换,即华氏-摄氏或摄氏-华氏 该代码目前不起作用,但是,它会立即转换Celcius Fahrenheit并完全忽略我为获取用户输入而输入的std::cin。相反,每次我运行程序时,他们都会输入值0 #include<iostream> using namespace std; int main() { uns

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

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

该代码目前不起作用,但是,它会立即转换Celcius Fahrenheit并完全忽略我为获取用户输入而输入的
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;
}
#包括
使用名称空间std;
int main(){
无符号短整数华氏{},摄氏{};
炭单元;
cout单元;
如果(单位=‘c’){
摄氏度;
华氏温度=(摄氏度*9.0)/5.0+32;

cout在if条件下,使用
unit=='C'| | unit='C'
。可能输入的是大写。对于负值,删除
unsign
,对于浮动答案,将
int转换为double
。在else条件下
fahrenheit=(摄氏度*9.0)/5.0+32;
是错误的,它将是
摄氏度=(华氏度-32)*5.0/9.0

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

celsius = (fahrenheit - 32) * 5 / 9.0;
但是,您的代码是

fahrenheit = (celsius * 9.0) / 5.0 + 32;

1.您的
if
工作-.2.您的
else
分支错误。您输入
华氏温度
,然后用
摄氏度的计算覆盖其值(在本例中未初始化).@JeJo华氏
/
摄氏
的类型必须是浮点型,我不同意。计算是用双精度(提升)完成的,结果可能是有意的“四舍五入”。不过,我支持你对(不)符号的担忧。;-)