【问题标题】:Extracting double values from file into array将文件中的双精度值提取到数组中
【发布时间】:2015-02-09 12:20:37
【问题描述】:

我正在尝试从 2 个不同的文本文件中提取双精度值并将它们放入数组中。这是代码的sn-p:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    int p;
    cout<<"Enter number of ordered pairs: ";
    cin>>p;
    cout<<endl;
    double x[p];
    ifstream myfile("x.txt");
    while (myfile.good())
    {
        myfile>>x[p];
        cout<<x[p]<<endl;
    }
    double testx = x[4]+x[3]+x[2]+x[1]+x[0];
    cout<<endl<<"The sum of the values of x are: "<<testx<<endl<<endl;
    double y[p];
    ifstream myfile2("y.txt");
    while (myfile2.good())
    {
        myfile2>>y[p];
        cout<<y[p]<<endl;
    }
    double testy = y[4]+y[3]+y[2]+y[1]+y[0];
    cout<<endl<<"The sum of the values of y are: "<<testy<<endl<<endl;  system("PAUSE");
    return EXIT_SUCCESS;
}

自从通过testxtexty 进行检查后,我认为这些值没有被正确存储,这些值的总和不是预期的。

【问题讨论】:

  • 您正在打印出这些值,因此您可以基于该值而不是总和来进行假设。什么是输入,输出预期输出(包括打印出来的值)。
  • 您无法使用变量p 调整数组x 的大小。大小需要在编译时知道,而不是运行时(除非某些编译器扩展)

标签: c++ arrays fstream


【解决方案1】:

您正在写入超出数组范围:您正在写入x[p]y[p],其中xy 是大小为p 的数组,因此有效索引来自@987654328 @到p-1

更不用说运行时大小的数组不是标准的 C++ 了。一些编译器(例如 GCC)支持它们作为扩展,但最好不要依赖它们。

当您在 C++ 中需要动态大小的数组时,请使用 std::vector

int p;
cout<<"Enter number of ordered pairs: ";
cin>>p;
cout<<endl;
std::vector<double> x;
ifstream myfile("x.txt");
double d;
while (myfile >> d)
{
    x.push_back(d);
    cout<<b.back()<<endl;
}

y 的 DTTO。

请注意,我更改了循环条件——您没有测试输入操作的结果。 More info.

此外,如果数字是任意浮点值,请记住它们cannot be simply compared for equality 在许多情况下,由于舍入错误和表示不精确。

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 2015-07-23
    • 2022-11-19
    • 1970-01-01
    • 2010-09-27
    • 2020-07-11
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多