C++ Illegal else

C++ Illegal else

本文关键字:else Illegal C++      更新时间:2023-10-16

好吧,我想制作一个简单的IPO循环,要求Wahrenheit或Celsius转换,然后根据他们的选择转换用户输入。我想我已经知道了,但是我的其他条款弄乱了。我无法弄清楚,在看了很长时间之后,也许新鲜的眼睛可以更轻松地指出我的错误?

代码:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int _tmain()
{
    int choice;
    double fahr, cel;
        cout << "Please choose 1 for fahrenheit, or 2 for Celsius: ";
        if (cin >> choice) {
            while (cin >> choice){
                if (choice == 1)
                    cout << "Enter Fahrenheit degrees to be        converted: " << endl;
                cin >> fahr;
                cel = (fahr - 32.0) / 1.8;
                cout << cel << " degrees" << endl;
                if(choice == 2)
                    cout << "Enter Celsius degrees to be converted: " << endl;
                cin >> cel;
                fahr = 9.0 / 5.0 * cel + 32.0;
                cout << fahr << " degrees" << endl;
                else {
                    cout << "Not a valid option";
                }
            }
        }
    return 0;
}

在需要定义代码范围时添加括号{}

这样:

if (choice == 1)
{
    cout << "Enter Fahrenheit degrees to be        converted: " << endl;
    cin >> fahr;
    cel = (fahr - 32.0) / 1.8;
    cout << cel << " degrees" << endl;
}
if(choice == 2)
{
    cout << "Enter Celsius degrees to be converted: " << endl;
    cin >> cel;
    fahr = 9.0 / 5.0 * cel + 32.0;
    cout << fahr << " degrees" << endl;
}
else 
{
    cout << "Not a valid option";
}

您没有在您的IF周围放卷曲牙套:

if (choice == 1){
            cout << "Enter Fahrenheit degrees to be        converted: " << endl;
            cin >> fahr;
            cel = (fahr - 32.0) / 1.8;
            cout << cel << " degrees" << endl;
}
else if(choice == 2){
            cout << "Enter Celsius degrees to be converted: " << endl;
            cin >> cel;
            fahr = 9.0 / 5.0 * cel + 32.0;
            cout << fahr << " degrees" << endl;
}
else {
            cout << "Not a valid option";
}

我认为您需要做2件事:1.使用支架支架包围所有条件应执行的所有语句。这将阐明该语句的范围。2.如果使用其他情况,则更改第二个,假设您希望用户输入选项1或2,但不能同时使用。

您错过了两个if s中的括号。当遇到if时,它仅执行cout语句。如果您希望它执行多个语句,则应添加卷曲括号{}