C++ Variable keeps resetting to 0 - c++

So I've got this simple piece of code. What it's supposed to do is calculate centigrade from Fahrenheit. For some reason, however, it keeps resetting the value of cent to 0. Can anyone please explain why it's doing this? I'm sure I'm just missing something small and stupid.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main (void)
{
ofstream fout("temps.dat");
float fahr=0, avgcent=0, avgfahr=0, totalcent=0, totalfahr=0, gettemp=0;
double cent = ((5/9) * (fahr - 32));
const int gatekeeper=-99999;
fout << setw(25) << "Fahrenheit" << setw(20) << "Centigrade" << endl << endl;
fout.setf(ios :: fixed);
fout.setf(ios :: showpoint);
cout << "Please input Fahrenheit temp (-99999 to quit)" << endl;
cin >> fahr;
while (fahr != gatekeeper)
{
totalfahr = totalfahr + fahr;
totalcent = cent + totalcent;
cout << cent;
cin >> fahr;
}//End of while (gettemp != gatekeeper)
}//End of int main (void) for HW2

In your line double cent = ((5/9) * (fahr - 32));, the expression (5/9) resolves to 0 because it uses integer division. Replace it with (5.0/9.0) and you should get the correct result.

Related

How to make it possible

My topic may be confusing, this is my code in C++,how can i display the summary of number of student count for each Grade at the end of the program,can any body help in this?
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
This is the output i want,can anybody helP?
This is my actual output
[Output of the program][1]
edit: thanks for the responses, since im currently taking a required programming class, and while ive had literally 100% of the material before, I had it all in C++, so im not very good with the syntax yet, and we are told only with functions/loops/methods that have been discussed in lecture , looks like i still need to put more effort into it.
I'm not sure if I understand the problem correctly, but you could increment specified counters each time you determined the grade in your if-else-cascade and then std::cout the results after the while loop.
You could try what Wum suggested, so the code might look like this:
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
char date[9];
ifstream in;
ofstream out;
string name;
char grade;
double asg1, asg2, test, quiz, exam, coursework, overallScore, numbergrade;
int numStudentsA = 0;
int numStudentsB = 0;
int numStudentsC = 0;
int numStudentsD = 0;
int numStudentsF = 0;
in.open("Student.txt");
out.open("Result.txt");
in >> name >> asg1 >> asg2 >> test >> quiz >> exam;
//to keep reading the data in input file
while (!in.eof()) {
coursework = asg1 + asg2 + test + quiz;
overallScore = coursework + exam;
if (overallScore >= 70 ) {
grade = 'A';
numStudentsA++;
}
else if (overallScore >= 60) {
grade = 'B';
numStudentsB++;
}
else if (overallScore >= 50) {
grade = 'C';
numStudentsC++;
}
else if (overallScore >= 40) {
grade = 'D';
numStudentsD++;
}
else if (overallScore >= 0) {
grade = 'F';
numStudentsF++;
}// grade
out << left << setw(15) << name ;
out << left << setw(3) <<coursework ; //coursework
out << left << setw(3) << exam ; //exam
out << left << setw(4) << overallScore ; //overall score
out << grade ;
out << endl;
in >> name >> asg1 >> asg2 >> test >> quiz >> exam;
}
cout << "Result Summary Date: " << date << endl;
cout << "Subeject: Programming Methodology" << endl;
cout << "Grade" << setw(10) << "Student" << endl;
cout << "A" << setw(10) << numStudentsA << endl;
cout << "B" << setw(10) << numStudentsB << endl;
cout << "C" << setw(10) << numStudentsC << endl;
cout << "D" << setw(10) << numStudentsD << endl;
cout << "F" << setw(10) << numStudentsF << endl;
cout << "Total Student = 10" << endl;
return 0;
}
I applied a bit of indentation to your code, try to use a single coding style. Also, you should read why the use of eof() is not recommended.
use a array to count the number of students for each grade and print out the array at the end.[ look for inline comments ]
Using a enum to index into the array for easy readability.
Instead of an array you could use maps was one of the suggestions .
eof in the above case is fine as , The first read is outside the while loop and then the check is done at the start. Also the subsequent reads are at the end of the while so the program will loop back right after the read to check the eof conditions and exit (without processing an empty buffer).
The code below checks for while (in>>name>>asg1>>asg2>>test>>quiz>>exam)
#include <iostream>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <vector>
enum { GRADE_A = 0 , GRADE_B = 1, GRADE_C = 2 , GRADE_D = 3 ,GRADE_F = 4}; // use an enum to index into the array for each grade
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
char date[9];
_strdate(date);
ifstream in;
ofstream out;
int grades[5]; // to store the grades count
string name;
char grade;
double asg1,asg2,test,quiz,exam,coursework,overallScore,numbergrade;
in.open("Student.txt");
out.open("Result.txt");
grades[GRADE_A] = 0 ; grades[GRADE_B] = 0 ; grades[GRADE_C] = 0 ; grades[GRADE_D] = 0 ; grades[GRADE_F] = 0 ; // initialize array
while (in>>name>>asg1>>asg2>>test>>quiz>>exam) //to keep reading the data in input file
{
coursework = asg1 + asg2 + test + quiz;
overallScore = coursework + exam;
if (overallScore >= 70 )
{grade = 'A' ;grades[GRADE_A]++;} // increment count for each grade
else if (overallScore >= 60)
{grade = 'B' ;grades[GRADE_B]++;}
else if (overallScore >= 50)
{grade = 'C' ;grades[GRADE_C]++;}
else if (overallScore >= 40)
{grade = 'D' ;grades[GRADE_D]++;}
else if (overallScore >= 0)
{grade = 'F' ;grades[GRADE_F]++;}; // grade
out<< left << setw(15) << name ;
out<< left << setw(3) <<coursework ; //coursework
out<< left << setw(3) << exam ; //exam
out<< left << setw(4) << overallScore ; //overall score
out<< grade ;
out<< endl;
}
cout<<"Result Summary Date: " << date << endl;
cout<<"Subeject: Programming Methodology"<<endl;
cout<< "Grade"<< setw(10) << "Student" <<endl;
cout<< "A" <<setw(10)<<grades[GRADE_A]<<endl; // output grade count
cout<< "B" <<setw(10)<<grades[GRADE_B]<<endl;
cout<< "C" <<setw(10)<<grades[GRADE_C]<<endl;
cout<< "D" <<setw(10)<<grades[GRADE_D]<<endl;
cout<< "F" <<setw(10)<<grades[GRADE_F]<<endl;
cout<<setw(0)<<endl;
cout<<"Total Student = 10"<<endl;
//At the end of the program, display the summary of number of student count for each Grade

Adding a Probability Equation Into the Program

I've been working on this program in which it should calculate the probability based on the following formula:
𝑃(𝑥) = (𝑁!) / (𝑥!) * (𝑁−𝑥)!) * (p^x) * ((1-p)^(N-x))
Also, when the user types in a value, N must be an integer, x must be an integer which can be between 0 and N, and p must be a positive real number between 0 and 1. Till now this part works just fine but I don't know how to properly add the probability formula in the program.
The following is my code so far:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
long int factorial (int N, int x, int p);
int main ()
{
double N, x, p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
return 0;
}
Can anyone help me out just to understand how to properly add an equation in my program?
Thank you!
This is my new code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double factorial (double N, double x, double p);
int main ()
{
double N;
double x;
double p;
cout << "Input N value" << endl;
cin >> N;
cout << "Input x Value" << endl;
cin >> x;
while(x<=0 || x>=N){
cout << "x value is NOT between 0 and N." << endl;
cout << "Input x Value" << endl;
cin >> x;
}
cout << "Input p value" << endl;
cin >> p;
while(p<=0 || p>=1){
cout << "p value is NOT a real number between 0 and 1." << endl;
cout << "Input p value" << endl;
cin >> p;
}
double Probability;
Probability = factorial(N, x, p);
cout << "Probability= " << Probability << endl;
return 0;
}
double factorial (double N, double x, double p){
double answer = ((tgamma(N+1))/((tgamma(x+1)) * (tgamma((N-x)+1)))) * (pow(p,x)) * (pow((1-p),(N-x)));
return answer;
}
The program recognizes the values I put in the system but when it calculates the answer, it gives a really small number. I tried out each section of the formula to make sure their was not a mistake but everything works fine when I tested it independently. Does anyone know what's wrong with the equation?
Thank you!
First you need to write a factorial function, check out this stackoverflow link:
How do you implement the factorial function in C++?
Then just write a function for your calculation. Assuming your factorial function is called getFact(int n) then:
double solve(int N, int x, double p) {
double answer = ( getFact(N)/getFact(x) )*getFact((N-x))* pow(p,x)* pow((1-p),(N-x));
return answer;
}
Then call the solve function in your main after having set your values.
double P_x;
P_x = solve(N,x,p);
Also, I use doubles because they can be more accurate, especially for p since its is 0 <= p <= 1.

Currency Conversion Program

I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);

mismatch in formal parameter list: unable to resolve function overload

So, writing my first program! Any hints about the errors above will be appreciate!! :)
I'm getting mismatch formal parameter list and unable to resolve function overload.
many many thanks,
#include <iostream>
#include <cmath>
#include "COMPFUN.H"
using namespace std;
int main()
{
double futureValue = 0.0;
double presentValue = 0.0;
double interestRate = 0.0;
cout << "Please enter Present Value: ";
cin >> presentValue;
cout << "Please enter rate: ";
cin >> interestRate;
futureValue = ( presentValue * 1 + interestRate / 1200.0 , 36) << endl;
cout << "Future value is: " << futureValue << endl;
system("pause");
return 0;
}
What do you expect the
futureValue = ( presentValue * 1 + interestRate / 1200.0 , 36) << endl;
endl to do at the end of this line? Do you want to shift the result by endl bits? Do you want a \n appended to futureValue and have it flushed afterwards?

How to read the entire value of a double using cin?

long double m;
cout << "enter double: "; cin >> m;
cout << "m = " << m <<endl;
Input:
enter double: 1.546640625
Output:
m = 1.54664
I have to convert into a binary with point, and when I read numbers like 2.359375000
Output:
m = 2.35938
And it works, but I think the problem is the zero in 1.546640625
You have read the whole value of the double. The problem is with the cout. It by default rounds the value to 6 digits after the decimal point.
To set the precision cout uses, use setprecision from <iomanip>:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long double d;
cin >> d;
cout << setprecision(10) << d << endl;
return 0;
}