c++ - cout 不显示 double 值

标签 c++ user-input

在程序中,我必须创建一个函数来填充 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/

相关文章:

用于两个线程之间通信的C++多线程数据结构

c++ - 无需暂停代码的用户输入(C++ 控制台应用程序)

c++ - 迭代器指向 "find_if"匹配后的第一个元素,为什么?

c++ - 除法表达式的数值稳定性

c# - 按下 ALT+KEY 时处理 KeyDown 事件

c++ - 如何读取二进制数作为输入?

python - 从文件中读取以不同方式编写的列表

java - 循环 try-catch 不起作用

其他库中类型之间的 C++ 转换运算符

c++ - linux/MSVC 2012 中的管道不稳定行为