if语句下只有一个语句正在运行
only one statement under if statement being run
我用C++编写了一个程序,要求输入任何整数。程序仅在两次迭代后就崩溃了。代码如下:
#include<iostream>
int main()
{
int user_choice;
std::cout <<"Please enter any number other than five: ";
std::cin >> user_choice;
while(user_choice != 5)
{
std::cout <<"Please enter any number other than five: ";
std::cin >> user_choice;
if(user_choice == 5)
std::cout << "Program Crash";
break;
}
std::cout << "I told you not to enter 5!";
return 0;
}
然后我试着这样做:
if(user_choice == 5)
std::cout << "Program Crash";
//std::cout << "Shutting Down";
这起到了作用。为什么注释掉第二行,会导致程序运行良好?
此代码:
if (counter == 10)
std::cout << "Wow you still have not entered 5. You win!";
user_choice = right_answer;
相当于:
if (counter == 10)
{
std::cout << "Wow you still have not entered 5. You win!";
}
user_choice = right_answer;
您的问题变得显而易见,user_choice = right_answer
不是仅在counter == 10
时执行的。因此,将其移动到if () { ... }
块内:
if (counter == 10)
{
std::cout << "Wow you still have not entered 5. You win!";
user_choice = right_answer;
}
C++不尊重缩进;所以当你写:
if (counter == 10)
std::cout << "Wow you still have not entered 5. You win!";
user_choice = right_answer;
编译器看到:
if (counter == 10)
std::cout << "Wow you still have not entered 5. You win!";
user_choice = right_answer;
要将两个语句都放在if
下,需要大括号:
if (counter == 10) {
std::cout << "Wow you still have not entered 5. You win!";
user_choice = right_answer;
}
相关文章:
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 为什么我的两个 cin 语句没有在程序结束时运行?
- 如果语句不会在 do - while 循环中运行
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 我的fahrenheit-celcius程序会忽略我的if-else语句,并在每次运行该程序时将值更改为0
- 在后台循环,同时运行其他语句 C++
- c++:if 语句无法正常运行,并继续执行无效输出
- 否则,如果语句无法正常运行
- 在 cout 语句中首先运行什么?(C++17)
- C - 如果语句问题.代码将不会运行其他,否则
- 一个关于在函数中运行未调用语句的非常奇怪的错误
- 如果在不需要的情况下运行语句
- 我可以在开关(消息)语句的同时运行一段时间吗?(C )
- 断言语句无法正常运行
- 如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句
- C 程序运行不正确的其他语句
- 当我做出语句 root->right->right = newnode(7);注释,编译器显示运行时错误。谁能解释为什么?
- 在C程序中,如果在运行时忽略语句
- 使用条件语句在运行时选择不同的模板化矩阵类
- if 语句运行时错误