C ++非法

时间:2014-01-29 03:40:08

标签: c++ loops if-statement compiler-errors

好的,我想创建一个简单的IPO循环,要求进行华氏度或摄氏度转换,然后根据用户的选择转换用户输入。我想我已经得到了,但我的其他条款搞砸了。我无法弄清楚,看了这么久,也许新鲜的眼睛可以更容易地指出我的错误?

代码:

#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;
}

4 个答案:

答案 0 :(得分:1)

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

像这样:

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";
}

答案 1 :(得分:0)

你没有在你的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 :(得分:0)

我认为你需要做两件事: 1.使用大括号括起所有应为每个if条件执行的语句。这将澄清该if语句的范围。 2.如果假设您希望用户输入选项1或2但不输入两者,则更改第二个if if use if。

答案 3 :(得分:0)

你错过了两个if中的括号。遇到if时,它只执行cout语句。如果您希望它执行多个语句,您应该添加花括号{}