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);
}
Related
So for my program It is suposed to read from a file and display my information but the display is misbehaving. I have asked my collegues and they are unsure and I even asked my professor but he was unsure of what was causing the error. If anyone could help me I would be very very thankful and honnostly amazed
//LIBRARIES
#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdio.h>
#include <math.h>
#include <cmath>
#include <string>
#include <cstring>
#include <thread>
#include <stdexcept>
#include <limits>
#include <cctype>
using namespace std;
//STORED ARRAY NAMES AND FUNCTION NAMES
int fillArrays (string teamWin[], string teamLose[],
float theScore[], ifstream & final);
float pointAverage (float theScore[], float numberOfGames);
int teamsScoredForty (float theScore[], int gameNum);
int savedMax (float theScore[], int gameNum);
int savedMin (float theScore[], int gameNum);
void printStoredInformation (string teamWin[], string teamLose[],
float theScore[], int gameNum);
void finalDisplay (float theScore[], string teamWin[],
string teamLose[], int teamsOverForty,
float averagePoints, int maxSavedInfo, int minSavedInfo);
//START OF MAIN
int
main ()
{
ifstream final;
float theScore[100];
string teamWin[100];
string teamLose[100];
int gameNum;
float numberOfGames;
float averagePoints;
int teamsOverForty;
int maxSavedInfo;
int minSavedInfo;
gameNum = fillArrays (teamWin, teamLose, theScore, final);
numberOfGames = gameNum;
averagePoints = pointAverage (theScore, numberOfGames);
teamsOverForty = teamsScoredForty (theScore, gameNum);
maxSavedInfo = savedMax (theScore, gameNum);
minSavedInfo = savedMin (theScore, gameNum);
printStoredInformation (teamWin, teamLose, theScore, gameNum);
finalDisplay (theScore, teamWin, teamLose, teamsOverForty,
averagePoints, maxSavedInfo, minSavedInfo);
return 0;
}
//FINAL DISPLAY OF INFORMATION
void
finalDisplay (float theScore[], string teamWin[],
string teamLose[], int teamsOverForty[],
float averagePoints, int maxSavedInfo, int minSavedInfo)
{
cout << "AVERAGE = " << averagePoints << endl;
cout << "TEAMS WHO SCORED OVER 40 POINTS IN ONE GAME = " << teamsOverForty << endl;
cout << endl;
cout << endl;
cout << "TEAM WHO SCORED THE MOST POINTS IN ONE GAME" << endl;
cout << "WINNERS = " << teamWin[maxSavedInfo] << endl;
cout << "LOSERS = " << teamLose[maxSavedInfo] << endl;
cout << "FINAL SCORE OF WINNERS" << theScore[maxSavedInfo] << endl;
cout << endl;
cout << endl;
cout << "TEAM WHO SCORED THE LEAST POINTS AND STILL WON" << endl;
cout << "WINNERS = " << teamWin[minSavedInfo];
cout << "LOSERS = " << teamLose[minSavedInfo];
cout << "FINAL SCORE OF WINNERS = " << theScore[minSavedInfo];
cout << endl;
}
//INFORMATION STORAGE FOR ARRAYS
int
fillArrays (string teamWin[], string teamLose[],
float theScore[], ifstream & final)
{
int i = 0;
final.open ("superbowl.dat");
while (!final.eof ())
{
getline (final, teamWin[i]);
getline (final, teamLose[i]);
final >> theScore[i];
final.ignore (1, '\n');
i += 1;
}
final.close ();
return i;
}
//FUNCTION TO FIND AVERAGE OF THE TEAMS SCORE
float
pointAverage (float theScore[], float numberOfGames)
{
float sum;
float avg;
for (int i = 0; i < numberOfGames; i++)
{
sum = sum + theScore[i];
}
avg = sum / numberOfGames;
return avg;
}
//FUNCTION FOR ALL THE TEAMS WHO SCORED MORE THEN FORTY
int
teamsScoredForty (float theScore[], int gameNum)
{
int teamSavedScoreOverForty = 0;
for (int i = 0; i < gameNum; i++)
{
if (theScore[i] > 40)
{
teamSavedScoreOverForty = teamSavedScoreOverForty + 1;
}
}
return teamSavedScoreOverForty;
}
//FUNCTION TO FIND WHICH TEAM SCORED MORE THEN ANY OTHER TEAM AND WON
int
savedMax (float theScore[], int gameNum)
{
int val = -1;
int idx;
for (int i = 0; i < gameNum; i++)
{
if (val < theScore[i])
{
val = theScore[i];
idx = 1;
}
}
return idx;
}
//FUNCTION TO FIND WHICH TEAM SCORED LESS THEN ANY OTHER TEAM AND WON
int
savedMin (float theScore[], int gameNum)
{
int val = theScore[0];
int idx;
for (int i = 0; i < gameNum; i++)
{
if (theScore[i] < val)
{
idx = i;
}
}
return idx;
}
//FINAL DISPLAY FUNCTION FOR ALL OF THE INFORMATION ABOVE
void
printStoredInformation (string teamWin[], string teamLose[],
float theScore[], int gameNum)
{
int a = 1;
for (int i = 0; i < gameNum; i++)
{
cout << "SUPER BOWL " << a << endl;
cout << "NAME OF WINNING TEAM - " << teamWin[i] << endl;
cout << "NAME OF LOSING TEAM - " << teamLose[i] << endl;
cout << "TOTAL POINTS SCORED BY WINNERS - " << theScore[i] << endl;
cout << endl;
a = a + 1;
}
}
That is the main code that it is having errors with.
PackersChiefs35PackersRaiders33JetsColts16ChiefsVikings23ColtsCowboys16CowboysDolphins24DolphinsRedskins14
DolphinsVikings24SteelersVikings16SteelersCowboys21RaidersVikings32CowboysBroncos27Broncos27SteelersVikings
35SteelersRams31RaidersEagles2749ersBengals26RedskinsDolphins27RaidersRedskings3849ersDolphins38Bears
Patriots46GiantsBroncos39RedskinsBroncos4249ersBengals2049ersBroncos55GiantsBills20RedskinsBills37Cowboys
Bills52CowboysBills3049ersChargers49CowboysSteelers27PackersPatriots35BroncosPackers31BroncosFalcons34
RamsTitans23RavensGiants34Patriotsrams20BuccaneersRaiders48PatriotsPanthers32PatriotsEagles24Steelers
Seahawks21ColtsBears29GiantsPatriots17SteelersCardinals27SaintsColts31PackersSteelers31GiantsPatriots
21Ravens49ers34SeahawksBroncos43PatriotsSeahawks28BroncosPanthers24PatriotsFalcons34EaglesPatriots41
PatriotsRams13Chiefs49ers31BuccaneersChiefs31RamsBengals23
Between Each word is an enter, I am just not alloud to put it in on this website sadly. It says it looks like Spam
I tried to mess with the 2 different displays I have and I tried to even add more functions to kep things more organized but it did not work. I also spent a few hours trying to debug it.
In addition to the concerns expressed by other users in the comments, your output is broken because you have a typo in your input file on record 13. You repeated Bronco 27 twice and the file input function breaks because it expects two team names and then an integer. Instead it receives a team name followed by a number:
SUPER BOWL 12
NAME OF WINNING TEAM - Cowboys
NAME OF LOSING TEAM - Broncos
TOTAL POINTS SCORED BY WINNERS - 27
SUPER BOWL 13
NAME OF WINNING TEAM - Broncos
NAME OF LOSING TEAM - 27
TOTAL POINTS SCORED BY WINNERS - 0
//...
What is the correct solution?
What is the correct solution?
What is the correct solution?
My Code (which is obviously wrong):
<iostream> and <fstream> libraries are included.
int main() {
int num = 0;
int totalCount = 0;
std::ifstream inFile;
double average = 0.0;
int totalTwo = 0;
double total = 0.0;
const double VALUE_ONE = 858.5;
std::cout << "What is the number? ";
std::cin >> num;
std::cout << std::endl;
inFile.open("numbers.txt");
while (inFile >> num) {
totalCount += num;
}
total = num * VALUE_ONE;
average = total/totalCount;
totalTwo = total * num;
inFile.close();
return 0;
}
numbers.txt
When you do this:
std::cin >> num;
std::cout << std::endl;
inFile.open("numbers.txt");
while (inFile >> num) {
totalCount += num;
}
you're reading into num and then immediately overwriting it with data from the input file. Use two variables for the two inputs.
Your code doesn't really match what the instructions say to do.
You are reading the user's chosen multiplier into num, and then you are reading the numbers from the text file into num as well, losing the multiplier. And you are not keeping track of how many numbers are read from the file, which you need in order to calculate the average.
You need to add a few more variables to your code to separate things. Also, there is no need for your VALUE_ONE constant at all.
Try something more like this:
#include <iostream>
#include <fstream>
int main()
{
int multiplier = 0;
int total = 0, totalTwo = 0;
int quantity = 0;
int num = 0;
double average = 0.0;
std::cout << "After all numbers are read, what number would you like to multiply the total by? ";
std::cin >> multiplier;
std::cout << std::endl;
std::ifstream inFile("numbers.txt");
while (inFile >> num) {
total += num;
++quantity;
}
inFile.close();
average = double(total) / quantity;
totalTwo = total * multiplier;
std::cout << "Total = " << total << "\n" << "Average = " << average << "\n" << "Total * " << multiplier << " = " << totalTwo;
return 0;
}
Live Demo
I created a program to display an average from an array of numbers the user have decided to input. The program asks the user the amount of numbers he / she will input, then they input all positive numbers. The output for the average is always a decimal, how can I only display the whole number without any decimal points. Ex. 12.34 = 12 / 8.98 = 8
#include <iostream>
#include <iomanip>
using namespace std;
void sortingTheScores(double *, int);
void showsTheScoresNumber(double *, int);
double averageForAllScores(double, int);
int main()
{
double *scores;
double total = 0.0;
double average;
int numberOfTestScores;
cout << "How many test scores do you have? ";
cin >> numberOfTestScores;
scores = new double[numberOfTestScores];
if (scores == NULL)
return 0;
for (int count = 0; count < numberOfTestScores; )
{
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Value must be one or greater: " ;
cin >> scores[count];
}
count = count +1;
}
for (int count = 0; count < numberOfTestScores; count++)
{
total += scores[count];
}
sortingTheScores(scores, numberOfTestScores);
cout << "The numbers in set are: \n";
showsTheScoresNumber(scores, numberOfTestScores);
averageForAllScores(total, numberOfTestScores);
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << averageForAllScores(total,numberOfTestScores);
return 0;
}
void sortingTheScores (double *array, int size)
{
int sorting;
int theIndex;
double theNumbers;
for (sorting = 0; sorting < (size - 1); sorting++)
{
theIndex = sorting;
theNumbers = array[sorting];
for (int index = sorting + 1; index < size; index++)
{
if (array[index] < theNumbers)
{
theNumbers = array[index];
theIndex = index;
}
}
array[theIndex] = array[sorting];
array[sorting] = theNumbers;
}
}
void showsTheScoresNumber (double *array, int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
double averageForAllScores(double total, int numberOfTestScores)
{ double average;
average = total / numberOfTestScores;
return average;
}
You can use I/O manipulators here:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(0) << 1.231321 << '\n';
}
Output:
1
You can do it without using iomanip library:
std::cout.precision(0);
std::cout << 1.231321 << std::endl;
Then you'll simply get:
1
Just you need to use std::cout.precision() which is equivalent to std::setprecision() from iomanip library.
Edit:
The aforementioned solution is okay for smaller floating point values, but if you try something like 1334.231321, the std::cout will result displaying some scientific notation, something like:
1e+03
which is actually odd to read and understand. To solve it, you need std::fixed flag, you may write something like:
std::cout.precision(0), std::cout << std::fixed;
std::cout << 1334.231321 << std::endl;
Then it'll show:
1334
For numbers in a +/-2^31 range you can do:
cout << int(12.34) << " " << int(8.98) << endl;
which produces output
12 8
You may also want to consider rounding to the nearest integers. To do so
add a line
#include <cmath>
then do
cout << int(rint(12.34)) << " " << int(rint(8.98)) << endl;
this gives
12 9
I'm using filestreams, reading integers into an infile then reading those positive into an array directed to an outfile. I bubble sort the array and am required to find the average, variance, standard deviation, and prime numbers. I'm having trouble with my prime numbers function, it is not streaming anything into my file at all. Photo of my terminal here. It's also miscalculating my average. I've taken out my sorting and get data functions so it doesn't look messy.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
const int MAX = 30;
void getVariance(int[], int);
bool isPrime(int[], int);
double average(int[], int);
int main()
{
string inputfilename, outputfilename;
ifstream infile;
ofstream outfile;
int prime, n, sum =0, posnumbers[MAX], countp=0, countn=0\
;
double variance, stdv, avg=0;
cout << "Please enter the name of the input file: ";
cin >> inputfilename;
infile.open(inputfilename.c_str());
cout << "Please enter the name of the output file: ";
cin >> outputfilename;
///////////////////////postive ////////////////////////////
outfile.open(outputfilename.c_str());
if(!infile)
cout << "file not open for input" << endl;
else
{
prime = isPrime(posnumbers, n);
outfile << "=======================" << endl << endl;
outfile << "Positive #'s in the File" << endl;
for (int i=0; i<n; i++)
{
if (posnumbers[i]>=0)
{
countp++;
sum = sum + posnumbers[i];
outfile << posnumbers[i] << endl;
if (posnumbers[i] == prime)
outfile << posnumbers[i] << endl;
}
}
outfile << "average " << sum/n << endl;
outfile << "variance " << variance << endl;
///////////////////////// functions/////////////////////
bool isPrime(int posnum[], int n)
{
for (int i=2; i<=posnum[n]/2; i++)
if (posnum[n] % i ==0)
return false;
else
return true;
}
double average(int posnum[], int n)
{
double sum = 0.0;
for (int i=0; i<n; i++)
{
sum += posnum[n];
}
return sum / n;
}
bool isPrime(int posnum[], int n)
{
for (int i=2; i<=posnum[n]/2; i++)
if (posnum[n] % i ==0)
return false;
else
return true;
}
This will not work. The reason is that you immediately return true when the number is not divisible. For example, if posnum[n] is, let's say, 3, then your modulo check will fail and you are going to return true immediately, without checking all the other numbers that could potentially be divisors.
Furthermore, isPrime is currently checking only a single number for primality, but that isn't reflected in the calling code.
prime = isPrime(posnumbers, n);
Since isPrime returns bool, prime is now either 0 or 1.
if (posnumbers[i] == prime)
outfile << posnumbers[i] << endl;
This means that that line will only output all numbers being 0 or 1, depending on the value of prime. You should call isPrime for every element of posnumbers instead and print it if it returns true.
For isPrime, try the following:
bool isPrime(int posnum[], int n) {
for (int i = 2; i <= posnum[n] / 2; ++i) {
if (posnum[n] % i == 0) {
return false;
}
}
return true;
}
#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