如何在C ++程序中捕获负整数输入?

时间:2014-07-01 20:48:06

标签: c++ arrays integer negative-number

一个程序,它询问10个正整数并将它们分类为奇数或偶数正整数输入。该算法必须捕获负整数输入。输出将显示在两列中。奇数和偶数。

那么如何捕获否定并通知无效输出?或重新提示,直到找到正数?

这是我的程序代码......

int x=10;
int a[x];

cout<<"Input :";
cin>>a[x];

while(a[x]!<0) /*[Error] expected ')' before '!' token*/
{              /*[Error] expected primary-expression before '<' token*/
if(a[x]<0)     /*[Error] expected ';' before ')' token*/
 {             /*[Error] expected '}' at end of input*/
  cout<<"The input is negative try again";
  cout<<"Input:";
  cin>>a[x];
 }
else
 {
  a[x++];
 }
}
cout<<"ODD\tEVEN";

for(int y=0; y<=10; y++)
 {
  if(y%2==0)/*It separates the ODD and EVEN*/
   {
    cout<<" "<<a[y];
   }
  else
   {
    cout<<"\t"<<a[y]<<endl;
   }
  }
return 0;
}

这应该是正确的代码。 我从昨天起就一直在调试这个。

3 个答案:

答案 0 :(得分:4)

!<不是C ++运算符。你可能正在寻找:

while (a[x] >= 0)

您的程序还有其他一些错误;您可能希望在编译完成后尝试使用调试器。

答案 1 :(得分:1)

你的代码组织得不好,即使你设法修复错误,它也不会产生你想要的结果,我已经重新编写代码来检查负数并让用户输入最多10个数字,然后分成奇数和偶数组。这就是我想出的:

int input = 0;
int itr = 0; //iterator or count looping cycles
int arrayInt[10];
//read user input
while (itr < 10) //iterate while loop runs 10 times (0 - 9) = 10
{
   do
   {
       std::cout << "Enter a number" << itr+1 << ": ";
       std::cin >> input; //read user input
   } while (input <= 0);

   arrayInt[itr] = input; //store input in the array

   itr++; //iterate loop
}

//printing odd & even numbers from the array
itr = 0; //reset iterator

std::cout << "---------------------" <<endl;
std::cout << "Even\t\tOdd" <<endl;
cout << "---------------------" <<endl;
while (itr < 10)
{
    if (arrayInt[itr] % 2 == 0) //check if even
    {
        std::cout << arrayInt[itr] <<endl; //print on left
    } //check odd
    else
    {
        std::cout << "\t\t" << arrayInt[itr] <<endl; //print on right
    }
    itr++;
}

答案 2 :(得分:0)

我看到的第一件事是while(a [x]!&lt; 0),这是无效的语法。你是说[x]不小于零吗?那将是[x]&gt; = 0.检查它是否小于零然后重新提示用户更有意义。如果while循环发现它大于或等于零,则其中的第一个if语句不能触发。您的程序中还有其他错误和异常。例如,为什么要使用[x ++];?这只是增加x并丢弃一个[x],所以只需使用x ++;