In: Computer Science
Write a C++ program to read a data file containing the velocity of cars crossing an intersection. Then determine the average velocity and the standard deviation of this data set. Use the concept of vector array to store the data and perform the calculations. Include a function called “Standard” to perform the standard deviation calculations and then return the value to the main function for printing.
Data to use. 10,15,20,25,30,35,40,45,50,55.
Please use something basic.
CODE:
#include<iostream>
#include<bits/stdc++.h>
#include<vector>
#include<cmath>
using namespace std;
//function Standard accepts two parameters numbers vector list
and an int mean
//mean is the average of numbers in the vector list
float Standard(vector<int> numbers, int mean){
float variance = 0;
//firs calculating the variance
for(int i=0;i<numbers.size();i++){
variance += pow(mean - numbers.at(i),2);
}
//calculating the variance
variance = variance/numbers.size();
//square root of variance is the standard deviation
float stdDev = pow(variance,0.5);
//returning the standard Deviation
return stdDev;
}
//main method
int main(){
//declaring a vector
vector<int> numbers;
fstream file;
//opening the file
file.open("input.txt",ios::in);
int number;
//populating the vector list with the numbers in the txt
file
while(file>>number){
numbers.push_back(number);
}
int sum = 0;
//calculating the average of the numbers
for(int i=0;i<numbers.size();i++){
sum += numbers.at(i);
}
sum = sum/numbers.size();
cout<<"Average velocity: "<<sum<<endl;
cout<<"Standard Deviation:
"<<Standard(numbers,sum)<<endl;
//closing the file
file.close();
return 0;
}
_______________________________________
CODE IMAGES:
_____________________________________________
OUTPUT:
input.txt
numbers in the txt file should be entered in the same format for proper functioning of the code
input.txt:
10
15
20
25
30
35
40
45
50
55
_____________________________________________________
Feel free to ask any questions in the comments section
Thank You!