当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Code doesn't teminate on -1

问题描述:

This program reads input from user and store value in an array and stop when user enter -1 or number of entries reached to 100.

This code doesn't terminate when -1 is entered.

#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;

}

网友答案:

You declared Varible z inside loop again. int z, i = 0; -> int i = 0;

#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;
}
网友答案:

The below code will work you have problem with the scope of the variable

#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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: