0

这是一段简单的代码。实际上它是一个“填充数组”功能代码。

#include <iostream>
 using namespace std;
int main(){ 
   int size = 10; a[10]; numberUsed;
   cout << "Enter up to " << size << " nonnegative whole numbers.\n"
   << "Mark the end of the list with a negative number.\n";
   int next, index = 0;
   cin >> next;
   while ((next >= 0) && (index < size)){
      a[index] = next;
      index++;
      cin >> next;
   }
  numberUsed = index;
  for(int i = 0 ; i < numberUsed -1 ; i++){
 cout << a[i]  << endl;
  }
}

当用户输入整数时它工作正常。但是当我输入双精度值时,它应该转换该特定值。并为下一个输入的整数重复该值。所以现在输入 1 2 3 4 5 6.5 7 8 9 -1 。我得到以下输出 1 2 3 4 5 6 6 6 6 6 任何帮助将不胜感激。

4

2 回答 2

3

你告诉cin读取一个整数,所以这就是它要做的 - 一旦它看到一个对整数无效的字符,它就会停止。在这种情况下,它是'.'. 尝试读取更多整数只会继续失败,在您的情况下会保留next其先前的值。

如果要截断浮点值,请读入浮点变量,然后自己进行截断。

double next;
...
a[index] = (int) next;
于 2013-06-11T16:48:11.043 回答
2

读取整数值时(并且您的代码正在使用int next;,任何不是整数的内容都会“停止”每次读取其他内容的输入。由于在输入流中next达到 a 时为 6 '.',因此它将继续填充具有该值的数组,直到空间不足。

如果您检查输入的状态,例如if(!cin >> next) ... error handling ...;,您可以检测到何时出现问题。作为错误处理的一部分,您应该“忽略任何输入,直到出现空格”——cin.ignore(1000, ' ');这将是一个好的开始。您还需要重新设置错误标志cin,以免下次出现错误,cin.clear()这样做。

如果要输入浮点数,则需要使用floatdouble键入 for next(和数组a)。

于 2013-06-11T16:47:21.280 回答