为什么这段代码不能运行?[初级]

Why can't this code run? [Beginner]

本文关键字:运行 初级 不能 段代码 代码 为什么      更新时间:2023-10-16

我昨天刚拿起"跳进C++",决定自己冒险。熟悉"if"语句哦,很久以前使用Java,我这样做是为了好玩:

#include <iostream>
using namespace std;
int main()
{
    int first;
    int second;
    int choice;
    int final;
    cout << "Enter your first number:" <<;
    endl;
    cin >> first >> ;
    cout << "Enter your second number:" <<;
    endl;
    cin >> second >> ;
    cout << "Would you like to 1. Add 2. Subtract 3. Multiply 4. Or divide these                numbers?" << endl;
if (choice = 1){
    final = first + second;
    cout << "Your answer is: " << final <<;
    return 0;
}
if (choice = 2){
    final = first - second;
    cout << "Your answer is: " << final <<;
    return 0;
}
if (choice = 3){
    final = first * second;
    cout << "Your answer is: " << final <<;
    return 0;
}
if (choice = 4){
    final = first / second;
    cout << "Your answer is: " << final <<;
    return 0;
}
else{
    cout << "You probably typed something wrong! Remember, hit your number and hit enter, nothing else!" << endl;
    cout << "Ending program." << endl;
    return 0;
}
}

为什么这个程序不能正常运行?

检查相等性的运算符是 ==,而不是 =

=代表赋值,== 代表相等性测试。将if(choice = 1)更改为 if(choice==1),其余的if语句也是如此。

choice = 1将选择分配给 1,然后 if 语句检查choice是否不为零。 这意味着 if 语句的所有主体都将执行。 你的意思是choice == 1,它检查选择是否等于 1。

if语句中,您应该使用比较运算符(例如==),但您使用的是赋值运算符(=)。

查看此内容了解更多信息: http://en.wikipedia.org/wiki/Operators_in_C_and_C++

你还有更多问题:

cin >> first >> ;

请注意最后>>。这不是有效的代码,这是一个语法错误。你的编译器应该已经告诉你这一点。

你的程序中有很多这样的内容。删除最后一个没有值的>><<。这应该可以清除您的大部分错误。