C++ standard deviation - c++

#include <stdio.h> /* printf, scanf, puts, NULL */
#include <iostream> /* cin and cout functions */
#include <cmath> /*for power function etc.. */
#include <string> /*to let us use strings as inputs */
#include <sstream> /*allows conversion of strings to floats */
#include <fstream> /*has all the file input functions */
#include <cmath>
using namespace std; /*saves some typing*/
int main()
{
string Myline; //this will contain the data read from the file
ifstream myfile("StatNum2.txt"); //associate file with the input stream, note file must be in project directory with cpp file.
//need to put in correct filename in place of Filename.***
int n = 0;
float numPoints = 0.0;
int Points[200];
// Normal comment
/* Multi-line comment */
if (myfile.is_open())
{
cout << "File is open" << endl;
while (!myfile.eof()) //note the ! this means this loops reads through until the file closes
{
getline(myfile, Myline); //this reads a single line from myfile into Myline
stringstream convert(Myline);
if (!(convert >> Points[n])) //uses stringstream to convert Myline (which is a string) into a number and put it into an index of Points
{
Points[n] = 0;
}
cout << n;
cout << ' ';
cout << Points[n] << endl;
n++;
}
myfile.close();
numPoints = n;
cout << "Number of integers: " << numPoints << endl;
}
else
{
cout << "Could not open file" << endl;
}
int sum = 0.0;
for (int i = 0; i < numPoints; i = i + 1)
{
// Code here will be repeated as long as 'i' is less than 100.
sum = sum + Points[i];
}
cout << "Sum: " << sum << endl;
float average = sum / numPoints;
cout << "Average: " << average << endl;
int x = 0;
float sqdiff = 0.0;
for (int x = 0; x < numPoints; x = x + 1);
{
sqdiff = (Points[x] - average)*(Points[x] - average);
}
cout << "difference of squares:" << sqdiff << endl;
float stddev = sqrt(sqdiff/n);
cout << "Standard Deviation:" << stddev << endl;
I'm trying to find the standard deviation but am having some problems with the above code from line 65. The code produces the wrong result or says the Points[x] is undefined so not sure how to fix that
any help would be appreciated, thanks

Related

How to get this to print to the outfile? (c++)

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
bool done = false;
cout << setprecision(20) << endl;
ifstream infile("in.txt");
ifstream outfile("out.txt");
while(!infile.eof()) {
int sign = 1;
double pi = 0;
long n;
infile >> n;
for(long i = 1; i < n; i += 2) {
pi += sign/(double)i;
sign = -sign;
}
pi *= 4;
cout << "value of pi for n = " << n << " is " << pi << endl;
}
return 0;
}
This reads from a file and prints to the console but I can't get the code to print to the outfile. I've tried doing
outfile<< "value of pi for n = " << n << " is " << pi << endl;
But that doesn't seem to work
It does not write to the file because you defined outfile as an std::ifstream
ifstream is for input files.
Define it as an ofstream and it should work.
Example:
ofstream outfile("out.txt");

Reading a numbers from .dat file and then computing the standard deviation

I'm suppose to read numbers from a .dat file and then compute the standard deviation and also output the amount of the numbers in the file. I believe my mean and standard deviation functions are correct. It's the actually inputting of the numbers from the file to the functions that's throwing me off. Here's what I have so far.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
const int MAX_COUNT = 1000; //for max size of array
double Mean(double*, int); //calculates average of numbers
double Standard_Deviation(double*, int); //calculates standard deviation
void Magic_Number();
ifstream InFile;
int main()
{
Homework_Header();
string NameOfInputFile = "StdDev.dat";
InFile.open("StdDev.dat");
if (InFile.fail()) {
cout << "Cannot open file: " << NameOfInputFile << "\d";
exit(1);
}
int SamplePoint = 0;
double dataPoint[MAX_COUNT];
double sd = Standard_Deviation(dataPoint, MAX_COUNT);
while (InFile >> dataPoint)
{
void Magic_Number();
sd = Standard_Deviation(dataPoint, MAX_COUNT);
SamplePoint++;
if (InFile.eof())break;
}
cout << "The Standard Deviation is: " << sd << endl;
cout <<SamplePoint << " records process \n";
InFile.close();
if (InFile.fail()) {
cout << "Cannot close file: " << NameOfInputFile << "\d";
exit(-5);
}
cin.get();
return 0;
}
void Magic_Number()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
}
double Mean(double* numbers, int count)
{
double calculated_mean = 0.0;
for (int i = 0; i < count; ++i)
{
calculated_mean += numbers[i];
}
calculated_mean /= double(count);
return calculated_mean;
}
double Standard_Deviation(double* numbers, int count) // * is pointer: special variable that has a memory address as value
{
double std_dev = 0.0;
double average = Mean(numbers, count); //Mean of numbers
double temp_dev;
for (int i = 0; i < count; ++i)
{
temp_dev = numbers[i] - average; //sets temp_dev to be the deviation from the average
std_dev += temp_dev * temp_dev; //adds squares of the deviations
}
std_dev /= double(count);
std_dev = sqrt(std_dev); // square roots
return std_dev;
}
#include "pch.h"
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
using namespace std;
double Calc_Stand_Dev(ifstream &);
void Magic_Number();
ifstream InFile;
const int MAX_NUM = 1000;
int main()
{
string NameOfInputFile = "StdDev.dat";
InFile.open("StdDev.dat");
if (InFile.fail()) {
cout << "Cannot open file: " << NameOfInputFile << "\d";
exit(-3);
}
double sd = Calc_Stand_Dev(InFile);
cout << "The standard deviation is: " << sd << endl;
//cout << RecordCount << " numbers total are used to calculate the standard deviation. \n";
InFile.close();
if (InFile.fail()) {
cout << "Cannot close file: " << NameOfInputFile << "\d";
exit(-5);
}
cin.get();
return 0;
}
double Calc_Stand_Dev(ifstream & InFile)
{
double dataPoint[MAX_NUM], Avg, Variance, stdDev, sum = 0, sumSq = 0;
int RecordCount = 0;
for (int i = 0; i < MAX_NUM; i++)
{
InFile >> dataPoint[i];
Magic_Number();
sum += dataPoint[i]; //sums each new data point added from the file
sumSq += (dataPoint[i] * dataPoint[i]); //squares the data points and makes a sum out of it.
++RecordCount; // coutner for number of data points
if (InFile.eof())break;
}
Avg = sum / RecordCount;
Variance = (RecordCount * sumSq - sum * sum) / (RecordCount * (RecordCount - 1));
stdDev = sqrt(Variance);
cout << RecordCount << " numbers processed \n";
return stdDev;
}
void Magic_Number()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
}

Confused about taking file name from command line and stuff to it C++

My problem is that I cant get the getting the filename from the command line from the user, then using that filename to write the median, mode, and average. Im new to c++ so any tips or code fix would be great, and if you guys see anything else wrong please let me know, this is what I have, Im 99% done with it its just this filewriting thats giving me problems. Thank you
#include <iostream>
#include <fsteam>
#include <string>
using namespace std;
double Median(int [], int);
double Average(int [], int);
double Mode(int [], int);
int main(int argc, char *argv[])
{
ofstream outFile;
string filename = argv[1];
outputFile.open(filename.c_str());
if(!outFile)
{
cerr << "Error with the file.";
}
else
{
continue;
}
int *array;
int array_size;
cout << "How many students were surveyed? " << endl;
cin >> array_size;
if(array_size < 1)
{
cout << "Number of students surveyed must be greater than 1." << endl;
return(1);
}
else
{
array = new int [array_size];
}
cout << "Enter the number of movies each studen saw." << endl;
for(int i = 0; i < array_size; i++)
{
cout << "Student " << i+1 << ": " << endl;
cin >> array[i];
}
for(int i = 0; i < array_size; i++)
{
for(int j = i+1; j < array_size-1; j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
outFile << "Median: " << median << endl;
outFile << "Average: "<< average << endl;
outFile << "Mode: " << mode << endl;
return 0;
}
double Median(int arr[], int size)
{
double middle;
if(size%2 == 0)
middle = (arr[size/2] + arr[size/2-1])/2;
else
middle = arr[size/2];
return middle;
}
double Average(int arr[], int size)
{
double ave = 0;
for(int i = 0; i < size ; i++)
ave += arr[i];
ave = ave/size;
return ave;
}
double Mode(int arr[], int size)
{
int count, mode = 0;
for(int i = 0; i < size; i++)
{
count = 1;
while(arr[i] == arr[i+1])
{
count++;
i++;
}
if(count > mode)
mode = arr[i];
if(count > 1)
i--;
}
return mode;
}
You'll likely see something about this in the compiler, but I'll let you know anyways #include <fsteam> is <fstream>
I'm confused as to why you chose to put this
else
{
continue;
}
instead of nothing, since continue; just jumps to the end of the current iteration, which doesn't seem necessary here.
The rest of it seems fine. It's formatted to be easily read. If you have any errors post-testing, let me know.
EDIT: Sorry, I can't add comments yet, but in response to your comment, it's likely because of what I noted about <fstream> above. It's just a typo.
I tried it with following patch.
--- orig.cpp 2014-05-17 12:39:37.000000000 +0800
+++ new.cpp 2014-05-17 12:38:28.000000000 +0800
## -1,5 +1,5 ##
#include <iostream>
-#include <fsteam>
+#include <fstream>
#include <string>
using namespace std;
## -16,13 +16,13 ##
outputFile.open(filename.c_str());
- if(!outFile)
+ if(!outputFile)
{
cerr << "Error with the file.";
}
else
{
- continue;
+// continue;
}
## -64,9 +64,9 ##
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
- outFile << "Median: " << median << endl;
- outFile << "Average: "<< average << endl;
- outFile << "Mode: " << mode << endl;
+ outputFile << "Median: " << median << endl;
+ outputFile << "Average: "<< average << endl;
+ outputFile << "Mode: " << mode << endl;
return 0;
}
I think that as following.
first, You type incorrectly with fsteam -> fstream.
second, you type incorrectly with outFile -> outputFile.
third, you must don't use continue without loop.
As result, I suggest you have more focus about typing error.
Better to check the count command line arguments.
int main(int argc, char *argv[])
{
if(argc <2 )
{
cout << "Specify out file name as command line argument";
return 0;
}
. . . . .
. . . . .
}
for more details,
http://www.cprogramming.com/tutorial/c/lesson14.html

copying the actual values of a 2d array to another 2d array c++

I'm new to c++ and ive Been trying to wrap my head around this all day. I am trying to read a data file that contains an unknown amount of rows (teacher said wont be more than 100 rows though). Each row contains 4 integers whose values range from 0-100. The 4 columns represent student test scores over the course of a semester. Each line/row represents one student's scores. while each column represents 1 test. I am to set up a 2D array to read the scores into. The scores from the data file go into the first 4 columns and the average of all 4 tests calculated in column 5 for each student/row. I will have rows 0 through n-1 due to the fact that i dont know how many students/rows are in the file. On the nth row i calculate each position row[0 through 4] as the average of the entire column above it. The average grade of all the students calculated at the bottom of each column row(nth) and each students average for all four tests calculated in column 5. The average each students test average calculated at the bottom of column 5 (grades[nth row][5] ={average of all rows in column 5}
Im sure a little broader knowledge base would be extremely beneficial, but this was a homework assignment so i had to try. I think pointers would have been the most beneficial thing to understand for this assignment; however, i just havent gotten there yet.
This was my first attempt:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <sstream>
#include <cmath>
#include <vector>
using namespace std;
double grades [100][5] = {0};
int row = 0;
int column = 0;
int main() {
char line[100];
ifstream myfile("sturec.dat");
if(myfile){
while (getline(myfile, line)) {
if (line == char) {
//grades[row][column] =
cout << line << endl;
for (int i = 0; i <= line.length(); i++) {
if (line[i] != line[0]) && (i == " ") && (line[i+1] == char) {
column += 1;
}
else if (line[i] && line[i+1] && line[i+2] !== " ") {
grades[row][column] = {line[i] + line[i+1] + line[i+2]};
else if (line[i] && line[i+1] !== " " ) {
grades [row][1] = {line[i] + line[i+1]};
}
}
row += 1;
}
}
}
}
which i gave up on and started over with trying to create a vector of vectors to populate with the file. It took me a long time to figure out how to actually bring the data in from the file. Finally i resorted to:
#include //all the necessary libraries
using namespace std;
double grades[100][5] = {0}//the 2d array i had hoped to populate with the data from file
int main(){
ifstream myfile("filename");
rowCount = 0;
int t1, t2, t3, t4;
while(myfile >> t1 >> t2 >> t3 >> t4){
cout << t1 << " " << t2 << " " << t3 << " " << t4 << endl;
cout << "this is row 1 + : " << rowCount << endl;
//at this point i was just happy to have successfully read the file and printed the values.
rowCount ++;
}
for(int i = 0; i < 4; i++){
grades[rowCount][i]// this is where i got lost i tried multiple different things in attempt to populate "grades" by trying to create temp arrays to hold the values of t1,2,3,4 in order to parse them and place them in "grades", but to no avail. Any direction would be appreciated.
}
just to show some of my different approaches, i'll post the slightly different versions of similar code that i have.
``
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
double grades[100][5] = {0};
int main() {
ifstream myfile("sturec.dat");
int rowCount = 0;
int tempArray[100][4] = {0};
char test [4] = {0};
int i = 0;
while (myfile >> tempArray[rowCount][i]) {
cout << rowCount << endl << " " << i << endl;
cout << "temp array: " << tempArray<< endl;
while(i < 4){
i++;
rowCount++;
}
}
/*for (int c = 0; c <= rowCount; c++) {
for (int r = 0; r <= i; r++) {
grades[rowCount][i] = (tempArray[r][c]);
}
}
cout<< tempArray << endl << grades << endl;
*/
}
/*double final;
while (myfile >> grades[rowCount][test]) {
//cout << t1 << " " << t2 << " " << t3 << " " << t4 << endl;
cout << grades << endl;
cout << rowCount << endl;
//cout << grades[rowCount][]
rowCount ++;
}
}
*/
next
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
double grades[100][5] = {0};
int main() {
ifstream myfile("sturec.dat");
int rowCount = 0;
int tempArray[100] = {0};
int t1, t2, t3, t4;
while (myfile >> t1 >> t2 >> t3 >> t4) {
cout << t1 << " " << t2 << " " << t3 << " " << t4 << endl;
int test [4] = {0};
for (int i = 0; (i < sizeof(test) - 1); i++) {
grades[rowCount][i] = {tempArray};
}
}
double final;
while (myfile >> grades[rowCount][i]) {
cout << grades << endl;
cout << rowCount << endl;
//cout << grades[rowCount][]
rowCount ++;
}
vector < vector <int> > grades(100);
//vector <int> rows(4/*,0*/); // assigns 4 columns to rows vector with value of zero
//rows.assign(5,0);
int row = 0;
myfile.open("sturec.dat", ios::in); //opens file
if (myfile.is_open()) {
cout << "file opened" << endl;
string line;
vector<string> myLines;
while (getline(myfile, line)) { //gets lines using myfile and puts them in line
myLines.push_back(line);
cout << "string line contains: " << line << endl;
for (int columns = 0; columns <= 4 /*sizeof(rows)*/; columns ++) {
myfile >> grades[row][columns]; cout << "2" << endl;
}
row += 1;
}
}
else cout << "cannot open file" << endl;
myfile.close(); cout << "closed file" << endl;
return 0;
//cout << grades;
}
last one:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
ifstream myfile;
vector < vector <int> > grades(100);
//vector <int> rows(4/*,0*/); // assigns 4 columns to rows vector with value of zero
//rows.assign(5,0);
int row = 0;
myfile.open("sturec.dat", ios::in); //opens file
if (myfile.is_open()) {
cout << "1" << endl;
cout << "file opened" << endl;
string line;
vector<string> myLines;
while (getline(myfile, line)) { //gets lines using myfile and puts them in line
myLines.push_back(line);
cout << "string line contains: " << line << endl;
for (int columns = 0; columns <= 4 /*sizeof(rows)*/; columns ++) {
myfile >> grades[row][columns]; cout << "2" << endl;
}
row += 1;
}
}
else cout << "cannot open file" << endl;
myfile.close(); cout << "closed file" << endl;
return 0;
//cout << grades;
}
This one actually got me the first line of the file but i couldnt get this error to go away:
Run Command: line 1: 13531 Segmentation fault: 11 ./"$2" "${#:3}"
vector < vector <int> > grades(100);
initializes a vector containing 100 vector<int>s of size 0. To avoid the segmentation fault in your last example, you should either initialize this as
vector < vector <int> > grades(100,vector<int>(5,0));
or replace myfile >> grades[row][columns]; with something like
int tmp;
myfile >> tmp;
grades[row].push_back(tmp);

Using functions properly

I'm trying to use functions to process data from a .dat file, but I can't seem to get the functions to read the data correctly. On line 62, it's trying to calculate the low, high and average of the different temperatures recorded at three different heights, but the functions aren't processing any data. The average function should be dividing the total of the numbers by the count of the numbers, but it's not doing that. Plus, I can't get high or low to work. What am I doing wrong?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <conio.h>
#include <string>
using namespace std;
double qMeter = 0;
double hMeter = 0;
double oneMeter = 0;
int solDay = 0;
string garbage;
string localTime;
string decSol;
ifstream input;
ofstream output;
//function prototypes
double low(double lowTemp);
double high(double highTemp);
float average(double avgTemp);
int main()
{
input.open("curiosity234x.dat"); //opens input data file
output.open("output.dat"); //opens output data file
for (int i = 0; i < 4; i++) //gets rid of the first four lines
{
getline(input,garbage);
cout << endl;
}
while (!input.eof())
{
int count;
double newOneMeter;
double newHMeter;
double newQMeter;
if (solDay == 2) //processes data for the second solar day
{
input >> solDay >> localTime >> decSol
>> newOneMeter >> newHMeter >> newQMeter;
oneMeter = oneMeter + newOneMeter;
hMeter = hMeter + newHMeter;
qMeter = qMeter + newQMeter;
count++;
output << solDay << fixed << setprecision(1) << setw(5)
<< "Solar" << "Average" << "Low" << "High"
<< "Average" << "Low" << "High"
<< "Average" << "Low" << "High"
<< "Day" << "Temp" << "Temp" << "Temp" << "Temp" << "Temp"
<< "Temp" << "Temp" << "Temp" << "Temp"
<< fixed << setprecision(15) << "1 meter" << ".5 meters"
<< ".25 meters"
<< average(oneMeter) << low(oneMeter) << high(oneMeter)
<< average(hMeter) << low(hMeter) << high(hMeter)
<< average(qMeter) << low(qMeter) << high(qMeter);
}
if (solDay == 3) //processes data for the third solar day
{
input >> solDay >> localTime >> decSol
>> newOneMeter >> newHMeter >> newQMeter;
oneMeter = oneMeter + newOneMeter;
hMeter = hMeter + newHMeter;
qMeter = qMeter + newQMeter;
count++;
output << solDay << fixed << setprecision(1) << setw(5)
<< "Solar" << "Average" << "Low" << "High"
<< average(oneMeter) << low(oneMeter) << high(oneMeter)
<< average(hMeter) << low(hMeter) << high(hMeter)
<< average(qMeter) << low(qMeter) << high(qMeter);
}
}
cout << endl << "The output.dat file has been written and transmitted.";
/*
reads first line. Assigns first string to 'int solDay'
second to 'string time', third to decSol, fourth to oneMeter,
fifth to hMeter and sixth to qmeter. Meters should have setw().
*/
getch();
return 0;
input.close();
output.close();
}
//functions used in main
double low(double lowTemp)
{
int test = 10,000;
double least;
if (lowTemp < test)
{
lowTemp = test;
lowTemp = least;
}
return least;
}
double high(double highTemp)
{
int test = 10,000;
double most;
if (highTemp < test)
{
highTemp = test;
highTemp = most;
}
return most;
}
float average(double avgTemp)
{
avgTemp = avgTemp / count;
return avgTemp;
}
Look at the implementation of low for example:
int test = 10,000;
double least;
if (lowTemp < test)
{
lowTemp = test;
lowTemp = least;
}
return least;
If the if block executes, you assign the uninitialized least to lowTemp. And then regardless of whether it executes or not, you return the uninitialized least.
Why would you assign test to lowTemp only to then overwrite it with least?
Also 10,000 is not a integer literal representing ten thousand. You cannot put a comma in your literals to separate thousands. You must write 10000.