【问题标题】:How to trap negative integer inputs in C++ program?如何在 C++ 程序中捕获负整数输入?
【发布时间】:2014-07-01 20:48:05
【问题描述】:

一个程序询问 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;
}

什么应该是正确的代码。 从昨天开始我一直在调试这个。

【问题讨论】:

  • 你将很快超越你的界限。用x检查你在做什么。

标签: c++ arrays integer negative-number


【解决方案1】:

!&lt; 不是 C++ 运算符。您可能正在寻找:

while (a[x] >= 0)

您的程序还有其他几个错误;您可能想在编译后尝试使用调试器进行单步调试。

【讨论】:

  • 我必须更改整个程序。
【解决方案2】:

您的代码组织得不好,即使您设法修复了错误,它也不会产生您想要的结果,我已经重新编写了检查负数并让用户输入最多的代码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++;
}

【讨论】:

  • if (input &gt; 0) 可能应该被删除。您已经在 while 循环中完成了有效性检查。话虽如此,如果0 确实通过了,使用当前的if,您会增加计数但不存储值,这可能不是所需的行为。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多