代码在 -1 上不终止
Code doesn't teminate on -1
此程序读取用户的输入并将值存储在数组中,当用户输入-1或条目数达到100时停止。
当输入-1时,此代码不会终止。
#include <iostream>
using namespace std;
main (){
int c [100];
int i, z;
do {
int z, i=0;
cout << "Enter value the number (-1 to end input): ";
cin >> z;
if (z != -1) {
c[i] = z;
}
i++;
} while (z != -1 && i < 100);
cout <<"Total number if positive integer entered by user is: " << i-1;
}
变量z
和i
在do-while
循环之外声明
int i, z;
但名称相同,新变量在循环中声明。
do {
int z, i=0;
do-while
循环具有Block作用域。这导致变量的第二个声明是有效的,没有重新定义,因为它们有自己的作用域。循环中对z
和i
的操作操作循环中声明的变量。
由于循环的控制表达式不在循环的块范围内,因此该表达式访问在循环之前声明的变量
因此,"外部"z
和i
变量是"未受影响的",循环永远不会终止,并且是"无尽的"。
这个问题可以简单地解决,方法是删除循环中变量i
和z
的声明,并通过0:初始化"第一个"i
#include <iostream>
using namespace std;
main (){
int c [100];
int z;
int i=0;
do {
cout << "Enter value the number (-1 to end input): ";
cin >> z;
if (z != -1) {
c[i] = z;
}
i++;
} while (z != -1 && i < 100);
cout <<"Total number if positive integer entered by user is: " << i-1;
}
如果变量的作用域有问题,下面的代码将起作用
#include<iostream>
using namespace std;
main (){
int c [100];
int i, z;
i = 0;
do {
cout << "Enter value the number (-1 to end input): ";
cin >> z;
if (z != -1) {
c[i] = z;
}
i++;
} while (z != -1 && i < 100);
cout <<"Total number if positive integer entered by user is: " << i-1;
}
相关文章:
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 用于将C++代码转换为 Web 程序集的脚本未终止
- 运行代码时,c++ 会终止进程
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- VSCode C++终端进程已终止,退出代码为:1
- 代码在执行之前终止,并且没有从用户那里获取输入
- 终端进程终止,退出代码为:1有什么方法可以修复它吗
- linux mint进程上的代码块已终止,状态为-1
- 终止调用本机代码的 .Net 线程
- 当我输入非整数值时,我的二次方程代码终止,如何让它正确循环?
- 以下代码如何工作以及何时终止
- 为什么我的 C++ 应用以退出值 -1 终止,但某些代码逻辑未执行?
- 这段代码出了什么问题?它在第二个 cin 可以执行之前终止
- 我的链接列表程序在代码块编译器(X0000000005)中以状态-1073741819终止
- 声明终止cpp中的以下代码中出现错误
- Jni_createjavm()用退出代码1终止
- C++ WinSock Recv 在接收 0 数据时终止线程而不是返回错误代码
- 使用终止进程终止"mstsc.exe"进程时出现错误代码(5)访问被拒绝
- 将在C++中的内联函数中返回语句实际上返回并终止代码流
- 线程提前终止代码255