正整数输入 [英] positive integers entered

查看:125
本文介绍了正整数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Dev c ++

这是我的代码



I'm using "Dev c++"
Here's my code

#include <iostream>
using namespace std;

main()
{
	int c[100];
	int z;
	int i;
	do{
		int z, i=0;
		cout<<"Please enter number(-1 to end)"<<endl;
		cin>>z;
		if(z!=-1)
		{
			c[i]=z;
		}
		i++;
	}	while(z!=-1 && i<100);
	cout<<"the total number of positive integers entered"<<i-1;
}



问题是它没有终止......


the problem is its not terminating...

推荐答案

问题是一个范围。你有一个名为 i z 的变量在main中出现2次。一旦在函数的顶部,再次在do / while循环内部。



问题是你的while条件是检查前2的值,而内循环内的代码正在使用第二个2.



要修复它,删除循环内的声明并初始化第一个到0.



The problem is one of scope. You got variables named i and z appearing 2 times in the main. Once at the top of the function and again inside the do/while loop.

The problem is that your while condition is checking the values of the first 2,while the code inside the inner loop is working with the second 2.

To fix it, remove the declarations that are inside the loop and initialize the first i to 0.

#include <iostream>
using namespace std;

main()
{
    int c[100];
    int z, i=0;
    do{
        //int z, i=0;
        cout<<"Please enter number(-1 to end)"<<endl;
        cin>>z;
        if(z!=-1)
        {
            c[i]=z;
        }
        i++;
    }   while(z!=-1 && i<100);
    cout<<"the total number of positive integers entered"<<i-1;
}


Quote:

int z, i = 0 ;

这是一个错误。变量 i 应该在 do 循环之前(之外)进行初始化。





在我看来,使用休息会让你的意图更明确:



This is a mistake. Variable i should be initialized before (outside) the do loop.


In my opinion, using a break would make your intentions more explicit:

int main()
{
  int c[100];
  size_t n;
  for (n=0; n<sizeof(c)/sizeof(c[0]); ++n)
  {
    cout << "please enter a number (-1 to end)" << endl;
    cin >> c[n];
    if ( c[n] == -1) break;
  }
  cout << "the total number of positive integers entered is " << n << endl;
}


这篇关于正整数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆