I thought I can make life a little easier in data statistics by making a small program which returns the results of sampling distribution of the mean (with standard error). It does this part successfully but in an attempt to return the z-score by using the formula I found here, it returns -1#IND. My interpretation of that formula is:
((1 / (sqrt(2 * pi) * stdev)) * pow(e, (normalpow))
where
double normalpow = -0.5 * ((mean - popmean) * (mean-popmean) / stdev)
I did a little more investigating and found that (mean - popmean) * (mean - popmean) was evaluating to 0 no matter what. How can I get around this problem of normalpow evaluating to 0.
#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
using namespace std;
double number ;
double mean ;
double popmean ;
double stdev ;
double square = 2;
double e = 2.71828182845904523536;
double pi = 3.14159265358979323846;
double normalpow = -0.5*((mean-popmean)*(mean-popmean)/stdev);
int main ()
{
string continuer ;
do
{
cout << "Enter Sample Mean: " << endl;
cin >> mean;
cout << "Enter Population Mean: " << endl;
cin >> popmean;
cout << "Enter Standard Deviation: " << endl;
cin >> stdev;
cout << "Enter Sample Size: " << endl;
cin >> number;
if (stdev == 0)
cout << ((mean-popmean)/(number))<< endl;
else
{
cout << ((mean-popmean)/((stdev)/(sqrt(number))))<< endl;
cout << ((1/(sqrt(2*pi)*stdev))*pow(e, (normalpow)))<< endl;
}
cout << "If you want to continue, Press Y" << endl ;
cin >> continuer;
} while (continuer == "Y" || continuer == "y") ;
return 0;
}
Your problem is here:
double normalpow = -0.5*((mean-popmean)*(mean-popmean)/stdev);
At this point, mean, popmean and stdev have garbage values because they haven't been initialized. It sounds like what you want is a function.
double normalPow(double mean, double popmean, double stddev)
{
return -0.5*((mean-popmean)*(mean-popmean)/stdev);
}
Then call it in your main:
double normalpow = normalPow(mean, popmean, stdev);
Of course, you should check for stdev equal or close to 0. in the function.
using namespace std;
double number ;
double mean ;
double popmean ;
double stdev ;
double square = 2;
double e = 2.71828182845904523536;
double pi = 3.14159265358979323846;
double normalpow = -0.5*((mean-popmean)*(mean-popmean)/stdev);
These are all variables with static storage duration, so those without explicit initialisers are initialised to 0.
Hence mean, popmean and stdev are all 0 when normalpow is initialised, and that initialisation results in
double normalpow = -0.5*(0.0*0.0/0.0);
which gives a NaN.
You never change normalpow afterwards, so any computation involving it results in a NaN.
This depends on how mean and popmean are calculated. mean - popmean evaluates to zero, if they are identical: mean == popmean.
And the formula you are using is not correct cause you are not calculating the square of the standard deviation.
Related
This question already has answers here:
Accessing an array out of bounds gives no error, why?
(18 answers)
Closed 7 months ago.
data11.txt:
Length(l) Time(t) Period(T)
200 10.55 0.527
300 22.72 1.136
400 26.16 1.308
500 28.59 1.429
600 31.16 1.558
ill be taking data from this file above in my code
#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <iomanip>
/*Using data11.txt as reference, write code to read from the file. In a pendulum experiment certain data was recorded in order to calculate the acceleration due to gravity. All calculations should be in their SI units
Write a function to calculate the acceleration due to gravity as the slope of the graph to this equation.T=2πlg−−√.
What is the percentage error in your calculated value? Take g=9.8ms-2.
If the pendulum weighs 50g and is displaced at an angle of 30, what will it maximum kinetic energy value for each length of the string? Display your answer in table form. */
using namespace std;
double slope_gravity(double T1, double T2, double L1, double L2){//slope function
double T1_inverse = 1/pow(T1,2);
double T2_inverse = 1/pow(T2,2);
double difference_T = T2_inverse - T1_inverse;
double difference_L = (L2 - L1)/100;
double slope = (difference_T/difference_L);
return slope;
}
const int n = 4;
int main (){
ifstream mydata;
string capture;
float Length[n], Time[n], Period[n], acc_gravity;//declaring variable
mydata.open("Data11.txt");
if (mydata.is_open()){
for (int i=0; i<n+1; i++){
getline(mydata, capture);
mydata >> Length[i] >> Time[i] >> Period[i];
}
acc_gravity = slope_gravity(Period[1], Period[0], Length[1], Length[0]);//acceleration due to gravity calc
cout << fixed << showpoint << setprecision(1);
cout << "The Acceleration Due To Gravity Obtained Experimentally "
<< "from the data11 file is "<<abs(acc_gravity)<<"ms^-2"<<endl;
cout << "Calculating for Percentage error.............";
cout <<endl<<endl;
float percent_error = (abs(acc_gravity)- 9.8) * 100/9.8;//error analysis
cout << "Percent Error is "<< setprecision(2) << abs(percent_error)<<"%"<<endl;
cout << endl;
cout << "Calculating Max Kinetic Energy of pendulum weighing 50g being "
<< "displaced at an angle of 30\n";
cout << setprecision(4);
float velocity[n], x[n], y;//kinetic energy calc
double max_KE[n];
for (int j=0; j<n+1; j++){
x[j] = 2 * acc_gravity * Length[j]/100;
y = 1 - cos(30);
velocity[j] = sqrt(x[j] * y);
max_KE[j] = 0.5 * 50/1000 * pow(velocity[j],2);
}
cout<<endl<<endl;
cout << setprecision(1);
cout << "Length(m)\tMaximum Kinetic Energy(J)\n";//tabular form display
for (int k=0; k<n+1; k++){
cout << Length[k] <<"\t"<< max_KE[k] <<endl;
}
}
mydata.close();
return 0;
}
The objective of the program is in the first comment above.
At the end of the program, i'm supposed to print the values of length and Maximum Kinetic energy to the console in a tabular form.
However, in the array Length[0], it prints 31.16, but i extracted data from data11.txt, so there is supposed to be the value 200 instead.
The origin of the problem start with this for loop. The for loop works well by extracting values from data11.txt. so the value of Length[0] is 200 here.
i've tried to check why it is behaving this way. The problem starts here;
mydata.open("Data11.txt");
if (mydata.is_open()){
for (int i=0; i<n+1; i++){
getline(mydata, capture);
mydata >> Length[i] >> Time[i] >> Period[i];
}
But outside the forloop, Length[0] is 31.16. I also noticed that Time[4] has different value from input value which is supposed to be 31.16.
Please any help with this?
What you have noticed is called 'buffer overrun'.
float Length[n], Time[n], Period[n], acc_gravity;
// since 'n' is 4,
// so the valid range of subscript of Length/Time/Period are [0-3]
// That means, if you try to write to Length[4],
// that is invalid, often lead to ruin something else.
mydata.open("data11.txt");
if (!mydata.is_open())
{
fprintf(stderr,"failed to open datafile.\n");
return 1;
}
for (int i=0; i<n+1; i++){ // here the rang of 'i' is [0 - 4]
getline(mydata, capture);
mydata >> Length[i] >> Time[i] >> Period[i]; // so, when i==4,
// 'buffer overun' happens here.
// 'Time' could be ruined by 'Period'.
}
If you want to skip the 'header' line of input file,
one possible approach is :
"'getline()' once , then enter the loop".
Whatever you choose, just don't 'buffer overrun'.
Good luck.:)
I am trying to write a program that rounds a number to a certain decimal place that was specified by the user. It is a requirement to do this with both cout.fset and cout.precision, as well as with round and pow functions. In the end, the output of the program should be something like this:
123.4567
2
123.46
123.46
My main function used cout.fset and cout.precision, and it works fine. The problem is my double rounding function which uses round and pow. For some reason I am getting the following output:
123.4567
2
123.46
0.00
Why is it printing just zeros in that last line? I am new to programming and C++ as a whole so I would appreciate your help. Thank you. (I have a feeling it is a minor/beginner mistake I am overlooking but this is the extent of my knowledge at the moment)
#include <iostream>
#include <math.h>
using namespace std;
double rounding(int pp){
double d;
double k = std::pow(10, pp);
return std::round(d * k) / k;
}
int main(){
double p;
double d, round;
cin >> d;
cin >> p;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(p);
cout << d << endl;
round = rounding(d);
cout << round << endl;
return 0;
}
d in the rounding function is not initialized and have indeterminate value.
Try this:
#include <iostream>
#include <math.h>
using namespace std;
double rounding(double d, int pp){
double k = std::pow(10, pp);
return std::round(d * k) / k;
}
int main(){
double p;
double d, round;
cin >> d;
cin >> p;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(p);
cout << d << endl;
round = rounding(d, d);
cout << round << endl;
return 0;
}
I'm currently learning about functions in C++ and am currently working on a homework assignment with functions being the main thing.
Currently, I'm trying to make a grade calculator with every operation of the process being split into a function of its own.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void getHWGrades(int homeworks[], int size)
{
cout << "\nEnter the grades, out of 100 points, for the 9 homeworks you completed." << endl;
cout << "Note that Homework 10 is given to you for free, but is the same grade \nas homework 9.\n" << endl;
for (int i = 0; i < 9; i++)
{
cout << "Homework " << i + 1 << ": ";
cin >> homeworks[i];
while (homeworks[i] > 100 || homeworks[i] < 0)
{
cout << "Invalid grade, input homework grade again: ";
cin >> homeworks[i];
}
}
homeworks[9] = homeworks[8];
cout << "Homework 10: " << homeworks[9];
}
double quizAverage()
{
double quizPts;
cout << "Input your in class quiz average: ";
cin >> quizPts;
return quizPts;
}
double labAverage()
{
double labPts;
cout << "Input your lab average: ";
cin >> labPts;
return labPts;
}
double teamProject()
{
double teamPts;
cout << "Input your team project grade: ";
cin >> teamPts;
return teamPts;
}
int exam1()
{
int exam1Pts;
cout << "Input your exam1 grade: ";
cin >> exam1Pts;
return exam1Pts;
}
int exam2()
{
int exam2Pts;
cout << "Input your exam2 grade: ";
cin >> exam2Pts;
return exam2Pts;
}
double hwAverage(int homeworks[], int size)
{
double total = 0;
double homeworkAverage = 0;
for (int i = 0; i < size; i++)
{
total = total + homeworks[i];
}
homeworkAverage = (total*1.0) / 10;
return homeworkAverage;
}
double currentPoints(double& quizPts, double& labPts, double& teamPts, double& homeworkAverage, int& exam1Pts, int& exam2Pts)
{
double totalPts = ((quizPts / 100.0) * 10) + ((labPts / 100.0) * 10) + ((teamPts / 100.0) * 15) + ((homeworkAverage / 100.0) * 20) + ((exam1Pts / 100.0) * 10) + ((exam2Pts / 100.0) * 15);
cout << "\nYour current points (out of the 80 total available), stand at: " << totalPts;
return totalPts;
}
double currentAverage(double& totalPts)
{
double availableAverage = totalPts*(100.0 / 80);
cout << "\nYour current average is: " << availableAverage;
return availableAverage;
}
int main()
{
// keep the console from closing in visual studio
char charer;
double totalPts;
double quizPts, labPts, teamPts, homeworkAverage;
int exam1Pts, exam2Pts;
const int ARRAY_SIZE = 10;
int hwArray[ARRAY_SIZE];
getHWGrades(hwArray, ARRAY_SIZE);
quizAverage();
labAverage();
teamProject();
exam1();
exam2();
currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
cin >> charer;
}
My issue, which I believe lies in the functions currentPoints and currentAverage, is that when I run this totalPts outputs as -5.09078e+61 and as a follow up result with the currentAverage function, availableAverage outputs as -1.157e+62.
I'm sure that the issue has to do with how I'm passing the values from function to function (which I doubt I'm doing correctly).
How would I go about fixing this issue?
Thank you in advance.
You need to store the return value from currentPoints() function, like this.
totalPts = currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
Reason is, you declared "totalPts" as local variable in currentPoints().
"Local variables has function scope only, it is undefined to main function".
Do this for all other
functions(quizAverage,labAverage,teamProject,exam1,exam2, hwAverage,currentAverage)
I hope, this will solve the issue !!!
The problem is not about functions, it's about variables.
Let's take quizPts for instance:
In the main method, you declare this variable, but then you don't do anything with it before sending it to currentPoints. Therefore it has an undefined value when you do so (undefined often looks like random in C).
The other variable quizPts you use in quizAverage have the same name but is not the same for the compiler.
Try in your main:
quizPts = quizAverage();
You asked
How would I go about fixing this issue?
And the answer is "Use the debugging tool with "watches" window open in your favorite IDE".
It's always very difficult to find an error simply by re-reading the code, but in the debugger you can see all the values of your variables at each moment of time. Specifically, in this example, you would realize that your variables have garbage values from the very beginning (are not initialized), and this value never changes.
Using this approach you could find the reason yourself in time less than necessary to write this SO question. I hope this will help you to save your time in future.
The problem is you use the variables such as quizPts and labPts without storing any value in them. In your case, you have to store the return value of the function to the corresponding variable before using it. For example, do the same as the following statement:
quizPts = quizAverage();
I am using the following code to print out the code, and i doesn't show the correct area of the circle. it shows -215487854145 as the area of the circle..
please help me
the code below code:
kindly help me as i am new to this language, i think i did everything right please
#include <iostream>
using namespace std;
int main()
{
int a, r;
a = 3.14 * r * r ;
cout << "enter Radius";
cin >> r;
cout << "area of circle is";
cout << a;
return 0;
}
Two issues.
You are computing a using an unitialised value of r. The program behaviour is undefined. Move it after the cin >> r; statement.
Working in int could cause you issues with overflow. The largest possible value of an int in C++ can be as small as 32767. Use a double instead, and an improved value of PI. Note that the type of 3.14 * r * r is a double anyway, and you're currently forcing a conversion to int.
As for PI itself, it is not included in the C++ standard library. Consider
constexpr double pi = 3.14159265358979323846264338328;
or take one from a mathematics library if you're using one.
You used r in a calculation before you ever read in the value. Move it after you read it in.
cin >> r;
a = 3.14 * r * r ;
Unlike in mathematics,
a = 3.14 * r * r ;
does not define a relationship between a and r (it's not an equation).
Instead, it means "replace the current value of a with 3.14 times the square of the current value of r".
Since you haven't given r a value yet, the result is undefined.
You need to move the lines around a bit in order to not use values that don't exist yet.
You should also not use integers for this, but floating-point.
double r;
cout << "enter Radius";
cin >> r;
double a = 3.14 * r * r ;
cout << "area of circle is " << a;
#include <iostream>
using namespace std;
int main()
{
int a, r;
// your r was not initialized when you use it.
a = 3.14 * r * r ;
cout << "enter Radius";
cin >> r;
cout << "area of circle is";
cout << a;
return 0;
}
right answer:
#include <iostream>
using namespace std;
int main()
{
int a, r;
cout << "enter Radius";
cin >> r;
//after r being initialized.
a = 3.14 * r * r;
cout << "area of circle is";
cout << a;
return 0;
}
I have written a C++ program (supposed to be a money counter), I'm having some trouble with my code, I need the decimals to show up. I use cout instead of printf if that matters.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
// Strings and Integers
int dollars;
int pennies;
int nickles;
int quarters;
int halfDollars;
int dimes;
int fiveBill;
int tenBill;
int twentyBill;
int fiftyBill;
int hundredBill;
// Coin/Bill Amounts
int penny = 0.01;
int dollar = 1.00;
int nickle = 0.05;
int quarter = 0.25;
int halfDollar = 0.50;
int dime = 0.10;
int five = 5.00;
int ten = 10.00;
int twenty = 20.00;
int fifty = 50.00;
int hundred = 100.00;
// Enter Amount
cout << "Count your money!\n\n" << endl << "Hundred Dollar Bills: ";
cin >> hundredBill;
cout << "\nFifty Dollar Bills: ";
cin >> fiftyBill;
cout << "\nTwenty Dollar Bills: ";
cin >> twentyBill;
cout << "\nTen Dollar Bills: ";
cin >> tenBill;
cout << "\nFive Dollar Bills: ";
cin >> fiveBill;
cout << "\nOne Dollar Bills: ";
cin >> dollars;
cout << "\nHalf-Dollars: ";
cin >> halfDollars;
cout << "\nQuaters: ";
cin >> quarters;
cout << "\nDimes: ";
cin >> dimes;
cout << "\nNickles: ";
cin >> nickles;
cout << "\nPennies: ";
cin >> pennies;
// Add Together
cout << (hundred * hundredBill) + (fifty * fiftyBill) + (twenty * twentyBill) + (ten * tenBill) + (five * fiveBill) + (dollars * dollar) + (halfDollar * halfDollars) + (quarter * quarters) + (dime * dimes) + (nickle * nickles) + (penny * pennies);
system("PAUSE");
return 0;
}
Your problem:
int penny = 0.01;
penny is an int, the name is short for 'integral value'. 0.01 is of type double. If you assign a double (either as literal or from another variable) to any form of int (int, long int, short int, ...), only the integral part is assigned and the decimals are dropped (simply dropped, no rounding occurs - no matter how close the value is to the next greater integral one).
So penny actually holds only 0. Alike the other variables, dollar is 1, nickle again 0, ...
You have now two choices. Either, you convert all numbers to double, or you do a little trick by assigning all values in cents:
int penny = 1;
int dollar = 100;
This is what I would prefer. Then only when it comes to outputting you would do appropriate formatting:
printf("the value of my variable is %d.%.2d $\n", value / 100, value % 100);
Edit:
As many prefer outputting via std::cout and this gets rather a hassle, a way to do it conveniently would be the following:
class Formatter
{
int value;
friend std::ostream& operator<<(std::ostream& s, Formatter f);
public:
Formatter(int value)
: value(value)
{
}
};
typedef Formatter F, M;
std::ostream& operator<<(std::ostream& s, Formatter f)
{
char c = s.fill();
return s << f.value / 100 << '.'
<< std::setfill('0') << std::setw(2) << f.value % 100
<< std::setfill(c); // restore previous fill character!
}
Typedef is not necessary, of course, just to illustrate other names – select any one that seems most appropriate to you (F: Formatter, M: Money, D: Dollar, ...). Usage then:
std::cout << F(penny) << std::endl;
As stated, the problem is that you are trying to assign a decimal value to an integer variable.
What occurs, is that your input (in the case of decimal values) can either be interpreted as a double or a float -type variable by the compiler. During the assignment of the given input however, int or fully, an integer, can only hold a value without a fractional component. Compiler takes note of this, and simply narrows your given input into a value the int variable can hold. The compiler isn't interested about anything after the decimal point, and simply discards the rest.
Thus,
int a = 3.5 // int can't hold the decimal 0.5, narrows into 3
int b = 3 // int can hold this, no narrowing
double d = 3.5 // double can hold this, no narrowing
float f = 3.5 // float can hold this, no narrowing
A good way would be to replace all your integer variables with the type double. In this simple a program, you shouldn't have the need to use printf to format the input.
And in the case you are wondering, why would I want to use double instead of float.
Here is some additional information:
https://softwareengineering.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double
Should I use double or float?
If you want to keep integers, cast the result to a float or double. Then set precision to 2 digits and fixed format.
#include <iostream>
#include <iomanip>
...
float total = (float) ((hundred * hundredBill) + (fifty * fiftyBill) + (twenty * twentyBill) + (ten * tenBill) + (five * fiveBill) + (dollars * dollar) + (halfDollar * halfDollars) + (quarter * quarters) + (dime * dimes) + (nickle * nickles) + (penny * pennies));
cout << std::setprecision(2) << std::fixed << total << endl;
I use "cout" instead of "printf" if that matters.
No it won't matter with whatever output you were expecting.
Use all the variables you want to manipulate w.r.t. decimals as 'double' data type.