gpt4 book ai didi

c++ - double 值到 int 变量 - 意外输出

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:44 31 4
gpt4 key购买 nike

这是一段简单的代码。其实就是一个“填充数组”的函数代码。

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

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

最佳答案

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

如果你想截断一个浮点值,读入一个浮点变量然后自己截断。

double next;
...
a[index] = (int) next;

关于c++ - double 值到 int 变量 - 意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17049224/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com