在程序中,我必须创建一个函数来填充 double 类型数组中的元素,然后使用另一个函数 show() 显示它们。现在,当我输入一个简单的数字时,例如:1,2,3,4,5; show 函数不会显示这些数字,而是显示垃圾值,例如:8.586689e+273。
我不知道出了什么问题,尤其是当我在这里打开另一个程序时,它可以很好地打印数字。
这是代码:
#include<iostream>
int fill(double arr[], int);
void show(const double arr[], int);
void reverse(double arr[], int);
const int size = 5;
using namespace std;
int main()
{
double arr[size];
int limit = fill(arr,size);
show(arr,limit);
reverse(arr,limit);
show(arr,limit);
return 0;
}
int fill(double arr[], int size)
{
cout<<"Enter the values to fill the array: "<<endl;
int i,temp;
for(i=0;i<size;i++){
cout<<"Enter entry #"<<i+1<<" : ";
cin>>temp;
if(!cin){
cin.clear();
while(cin.get()!='\n')
continue;
cout<<"Bad Input.Input Process Terminated.";
break;
}
else if(temp<0){
break;
arr[i]=temp;
}
}
return i;
}
void show(const double ar[], int n)
{
using namespace std;
for(int i=0;i<n;i++){
cout<<"Entry #"<<(i+1)<<": ";
cout<<ar[i]<<endl;
}
}
void reverse(double arr[], int limit)
{
cout<<"Reversing values..."<<endl;
double temp;
for(int i=0;i<limit/2;i++){
temp = arr[i];
arr[i]=arr[limit-i-1];
arr[limit-i-1]=temp;
}
}
最佳答案
您没有填充该区域。请注意您尝试这样做的位置。您将其放在 temp<0 条件内、break 语句之后。因此它永远不会被执行。 由于您的数组未初始化(您应该使用 vector ),因此它包含无法正确显示的奇怪值。
int fill(double arr[], int size)
{
cout<<"Enter the values to fill the array: "<<endl;
int i,temp;
for(i=0;i<size;i++){
cout<<"Enter entry #"<<i+1<<" : ";
cin>>temp;
if(!cin){
cin.clear();
while(cin.get()!='\n')
continue;
cout<<"Bad Input.Input Process Terminated.";
break;
}
else if(temp<0){
break;
}
arr[i]=temp;
}
return i;
}
关于c++ - cout 不显示 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965384/