为什么这段代码不能运行?[初级]
Why can't this code run? [Beginner]
我昨天刚拿起"跳进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 >> ;
请注意最后>>
。这不是有效的代码,这是一个语法错误。你的编译器应该已经告诉你这一点。
你的程序中有很多这样的内容。删除最后一个没有值的>>
或<<
。这应该可以清除您的大部分错误。
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在C应用程序中运行C++(带有STL)函数
- 运行程序时出现问题
- 为什么这段代码不能运行?[初级]
- 初级C++:在不知道要创建多少对象的情况下在运行时创建对象