Hello,
I have written a program to input ten floating-point numbers from an input file, read them, and then sum the numbers and calculate the average. The program then outputs the sum and average to an output file. I am having two problems:
1. in Xcode, the program compiles and runs, but the output file contains:
0.00
0.00
2. in Visual C++, the output from "Build Solution" shows warning C4700; that is, that my variables are not initialized (i.e. n1, n2, n3, etc...). When I try to run the program, I get a window with "Debug Error! Run-Time Check Failure #3 - T", and I then have to abort the program.
I have tried initializing the variables in Xcode as:
int n1 = 92.34;
int n2 = 74.523;
etc...
without using any input and the average and sum are computed correctly and written to the output file.
For your reference floatinput.txt looks like this:
10.958
8.4442
63.42
4.99
0.392
46.27
12.123
93.42
1.02
94.265
What could I be doing wrong?
Thanks for your help,
lajm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <iostream>
#include <fstream>
// for declaring I/O streams with files
#include <iomanip>
// for using setprecision
using namespace std;
int main()
{
float n1, n2, n3, n4, n5, n6, n7, n8, n9, n10;
// declares 10 float variables to store the floating-point values
float sum = n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9 + n10;
float average = sum / 10;
// declares three float variables and uses the 10 floating-point values in the computation of the sum and average
// also declares number of floating-point values to be 10
ifstream dataIn;
ofstream dataOut;
// declares two internal file names to associate with an external file name
dataOut << fixed << showpoint;
// forces decimal display and shows the decimal even if there are no fractional components
dataIn.open("floatinput.txt");
dataOut.open("output.txt");
// associates internal file names to external file names and opens the files for use
dataIn >> n1 >> n2 >> n3 >> n4 >> n5 >> n6 >> n7 >> n8 >> n9 >> n10;
// reads data from external input file
dataOut << setprecision(2);
// sets precision of average to two numbers after the decimal point
dataOut << sum << endl;
dataOut << average << endl;
// writes the sum and average to the external output file
dataIn.close();
dataOut.close();
// closes input and output stream
return 0;
}
|