代码在 -1 上不终止

Code doesn't teminate on -1

本文关键字:终止 代码      更新时间:2023-10-16

此程序读取用户的输入并将值存储在数组中,当用户输入-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;
}

变量zido-while循环之外声明

int i, z;

但名称相同,新变量在循环中声明。

do {
  int z, i=0;

do-while循环具有Block作用域。这导致变量的第二个声明是有效的,没有重新定义,因为它们有自己的作用域。循环中对zi的操作操作循环中声明的变量。

由于循环的控制表达式不在循环的块范围内,因此该表达式访问在循环之前声明的变量
因此,"外部"zi变量是"未受影响的",循环永远不会终止,并且是"无尽的"。

这个问题可以简单地解决,方法是删除循环中变量iz的声明,并通过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;
}