提问者:小点点

转换器练习:跳过if和else if语句


我试图制作一个转换器,用户首先写入温度,然后选择要转换到哪个测量值。 如果我写一个数字,计算机会跳过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;
}

共1个答案

匿名用户

您似乎遗漏了选择变量的cin

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;
     
   cin >> selection;

   // if-statements
}