繁体   English   中英

C ++代码中的大量负输出

[英]Large negative output in C++ code

我需要编写一个程序,将5个浮点数存储到一个文件中,然后写一个将读取这些数字并显示它们的程序。 我正在使用C ++ Microsoft visual studio express 2012。

这是程序1:

// This program obtains 5 floating point numbers from the user,
// then saves these numbers to a file.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
// Define Variables
double num1;    
double num2;    
double num3;    
double num4;    
double num5;        

ofstream outputFile;
outputFile.open("homework3.txt");

// Get 5 floating point numbers
cout << "Please enter 5 floating-point numbers, all separtated by a space."<<endl;
cin >> num1 >> num2 >> num3 >> num4 >> num5;


// Store these numbers to the file
outputFile << num1 << endl;
outputFile << num2 << endl;
outputFile << num3 << endl;
outputFile << num4 << endl;
outputFile << num5 << endl;


// Close the file
outputFile.close();
cout << "Thank you!";

cin.ignore();
cin.get();

return 0; 
}

我可以找到我的文本文件,显示我输入的数字就好了。

那么这里的程序2:

// This program opens a file previously created, and displays
// the numbers and the sum of these numbers. 
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
// Define Variables
ifstream inFile;
double num1; 
double num2;
double num3;
double num4;
double num5;


// Open the file from program 1
inFile.open("homework3.txt");

// Read and Display the Numbers
inFile >> num1 >> num2 >> num3 >> num4 >> num5;
cout << num1 << endl << num2 << endl << num3 << endl << num4 << endl << num5 << endl;


inFile.close();

cin.ignore();
cin.get();

return 0;
}

我省略了关于找到总和的部分,因为它首先没有正确显示给我。

当我运行这部分时,我得到了

-9.25596e + 061-9.25596e + 061 -9.25596e + 061-9.25596e + 061-9.25596e + 061。

最有可能这些是垃圾值,并确保文件homework3.txt是正确的,并在程序中正确打开。

I / O经常会出现故障,因为计算机并不是很擅长猜测。 因此,您确实应该检查I / O操作是否成功:

if ( inFile >> num1 >> num2 >> num3 >> num4 >> num5 )
{
  // Worked !
}
else
{
  // Failed ! Something is wrong, and C++ won't guess.
}

实际上,您还应该检查open成功。 该文件是否在正确的目录中? 或者它可能在上一个练习的目录中?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM