Cannot compute equation, always gives zero - c++

Did i miss something? The variable percentage_ always equals 0. I've checked nTimes and winnings, they give the correct values as what is being input. Even when I test out a simple equation like, percentage_=1+1, percentage_ will give 0. Can someone help?
#pragma once
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;
class GuessMachine
{
private:
int nTimes;
int winnings;
string nM[6];
public:
GuessMachine();
void displayPrizes();
void displayMenu();
int getInput();
void checkNumber();
void checkPrize();
};
void GuessMachine::checkPrize()
{
MagicNumber mn;
int prize_=mn.generateNumber();
float percentage_;
percentage_ = float (winnings/nTimes*100); //<--On this line percentage is always 0 no matter what winnings and nTimes are
cout<<"Percentage is "<<percentage_<<endl;
if(percentage_ >= 50)
{
cout<<"You have scored "<<percentage_<<"% and won "<<nM[prize_];
}
else
{
cout<<"You have scored "<<percentage_<<"%. You lose!!";
}
cin.ignore();
cin.ignore();
}

Try
float (winnings) /nTimes*100
instead.
Your version still converts an int - 0 to a float.
If one operand to / is a float, it will work.

Change
percentage_ = float (winnings/nTimes*100);
to
percentage_ = (float(winnings))/nTimes*100;
since you need to change 1 number to float for the division to work on floats.

Related

Using member function to solve equation C++

I am currently trying to create a program to calculate the mass of a rocket with given time values by passing an array to a member function of a class. I get these two errors and can't seem to figure out how to get rid of them. Any suggestions are much appreciated, thank you.
23 8 [Error] prototype for 'double equip::calcmass(double)' does not match any in class 'equip'
13 10 [Error] candidate is: double equip::calcmass()
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstring>
using namespace std;
class equip
{
public:
double mass[999999999], velocity, height, time[999999999];
double calcmass();
private:
double T = 7000;
double g = 32.2;
double K = 0.008;
};
double equip::calcmass(double time)
{
int i = 0;
for(i=0; i=999999999; i++)
{
return mass[i] = (3000 - 40 * time[i]) / g;
}
}
int main()
{
int i = 0;
equip rocket;
ifstream infile;
string filename;
cout<<"Enter input file name for time (time): ";
cin>>filename;
infile.open(filename.c_str());
while(infile.fail())
{
cerr<<"Error opening file. \n";
cout<<"Enter file name: ";
cin>>filename;
infile.open(filename.c_str());
}
for(i=0; i<999999999; i++)
{
infile>>rocket.time[i];
}
for(i=0; i<999999999; i++)
{
cout<<rocket.mass[i];
}
return 0;
}
In your class definition you've declared
double calcmass()
In the definition of the member function it's
double calcmass(double time)
They do not match. One takes a double as argument and the other does not.
You were missing a bunch of headers, and in the function declaration was missing the parameter presents in the function definition:
#include <cmath>
#include <cstring>
#include <fstream>
#include<iostream>
using namespace std;
class equip
{
public:
...
double calcmass(double time); // here was missing the parameter
...
};
double equip::calcmass(double time)
{
...
}
Also you are doing time[i] on time which is a double, so you can't use operator[]... If you want to pass an array, you can use pointer to double:
class equip{
...
double calcmass(double* time)
}
double equip::calcmass(double* time)
{
...
}

3D array picks up unrealistic values while compiling and not the ones already set

The following code is the first part to simulate molecular dynamics in 3D lattices. I'm having issues with the 3D array picking up garbage values.Not at all locations, but some because of which the entire result goes wrong.I've also noticed that the error occurs when the dimension of my array is 5*5*5 onwards(for this particular simulation the least length of the cube's side should be 3). Also the code takes suspiciously longer time to complete than expected.Please comment on that issue as well if possible. And please ignore the obvious comments like what each function does, I'd done it so that I don't forget. Thanks in advance.
#include <iostream>
#include <cstdlib> // has rand(),srand().
#include <ctime> // has time.
#include <fstream> // enables file handling.
#include <math.h>
using namespace std;
float rand_gen(); //full function written after main().
//int pbc(int,int,int);
int main()
{
srand((int)time(0)); //sets time as the seed for the random no. generation.
int dim=5;
int i,j,k,iup,idown,jup,jdown,kup,kdown;//indices
float x;
int l[dim][dim][dim];
float M=0.0,E=0.0;
for(i=1;i<=dim;i++)
{
for(j=1;j<=dim;j++)
{
for(k=1;k<=dim;k++)
{
x=rand_gen();
if(x<=0.5)
{
l[i][j][k]=-1; //sets the value in that particular location.
}
else
{
l[i][j][k]=1; //sets the value in that particular location.
}
M=M+l[i][j][k];
}
}
}
cout<<"Total magnetisation= "<<M<<endl;
for(i=1;i<=dim;i++)
{
for(j=1;j<=dim;j++)
{
for(k=1;k<=dim;k++)
{
if(i==1)iup=dim; //*********************************
else iup=i-1;
if(i==dim)idown=1;
else idown=i+1;
if(j==1)jup=dim;
else jup=j-1; //periodic boundary condition.
if(j==dim)jdown=1;
else jdown=j+1;
if(k==1)kup=dim;
else kup=k-1;
if(k==dim)kdown=1;
else kdown=k+1; // ends here//
E=E-(l[i][j][k]*(l[iup][j][k]+l[idown][j][k]+l[i][jup][k]+l[i][jdown][k]+l[i][j][kup]+l[i][j][kdown]))/2.0;
}
}
}
cout<<"Average E= "<<E/(dim*dim*dim)<<endl;
//cout<<"Testing: "<<l[5][4][3]<<" "<<l[5][4][3]<<endl;;
//**************************ALL FINE TILL HERE IT SEEMS****************************************************//
int n=100; //Number of iterations.
int no,site;
int ri,rj,rk,riup,ridown,rjup,rjdown,rkup,rkdown;
float eng=0.0,mag=M;float E_check=0.0;
float E_b4,E_aft,E_diff;
float T=4.2;
float a;
ofstream file ("Energy_check"); //file created to write the results into.
//ofstream file1 ("ENERGY1.txt");
for(no=1;no<=n;no++)
{
for(site=1;site<=(dim*dim*dim);site++)
{
float v1=rand_gen();
float v2=rand_gen();
float v3=rand_gen();
ri= int(v1*dim)+1;
rj= int(v2*dim)+1;
rk= int(v3*dim)+1;
//if((ri>=1&&ri<=dim)&&(rj>=1&&rj<=dim)&&(rk>=1&&rk<=dim))
{if(ri==1)riup=dim; //periodic boundary condition like above
else riup=ri-1;
if(ri==dim)ridown=1;
else ridown=ri+1;
if(rj==1)rjup=dim;
else rjup=rj-1;
if(rj==dim)rjdown=1;
else rjdown=rj+1;
if(rk==1)rkup=dim;
else rkup=rk-1;
if(rk==dim)rkdown=1;
else rkdown=rk+1; // ends here
}
E_b4=-(l[ri][rj][rk]*(l[riup][rj][rk]+l[ridown][rj][rk]+l[ri][rjup][rk]+l[ri][rjdown][rk]+l[ri][rj][rkup]+l[ri][rj][rkdown]))/2.0;
E_aft=-(E_b4);
E_diff=-2.0*(E_b4);
E_check=E_check+E_b4;
if(E_diff<0)
{
l[ri][rj][rk]=-l[ri][rj][rk];
eng=eng+E_diff;
mag=mag-2*l[ri][rj][rk];
}
else
{
a=rand_gen();
if(a<pow(exp(1.0),-E_diff/T))
{
l[ri][rj][rk]=-l[ri][rj][rk];
eng=eng+E_diff;
mag=mag-2*l[i][j][k];
}
}
if(file.is_open())
{ // THE FOLLOWING CODE IS SUPPOSED TO SHOW THE VALUES OF THE ARRAY CORRESPONDING TO ITS INDICES. bUT IM GETTING GARBAGE VALUES WHEN I RUN THIS.
file<<no<<" "<<ri<<rj<<rk<<" "<<l[ri][rj][rk]<<" "<<riup<<rj<<rk<<" "<<l[riup][rj][rk]<<" "<<ridown<<rj<<rk<<" "<<l[ridown][rj][rk]<<" "<<ri<<rjup<<rk<<" "<<l[ri][rjup][rk]<<" "<<ri<<rjdown<<rk<<" "<<l[ri][rjdown][rk]<<" "<<ri<<rj<<rkup<<" "<<l[ri][rj][rkup]<<" "<<ri<<rj<<rkdown<<" "<<l[ri][rj][rkdown]<<" "<<E_b4<<" "<<E_check<<endl;
}
}
E=(E+eng)/(dim*dim*dim);
/*if(file1.is_open())
{
file1<<no<<"\t"<<E<<endl;
}*/
}
file.close();
//file1.close();
cout<<"E_check_avg= "<<E_check/(dim*dim*dim)<<endl;
return 0;
}
float rand_gen() //function to generate random number.
{
return (static_cast <float> (rand()) / static_cast <float> (RAND_MAX));// random no. generated.
}

C++ error at the last line of code

I'm a begineer in C++ programming but I know the basics.
I recently started writing a simple game. The program chooses a random number
(1-100) and you have to guess it. There are 2 modes:
Normal - whenever you enter a number program tells you if it's bigger than the random or smaller.
hard - no clues, just pure luck.
Everything was running ok but when I added some fixes to the displayed text the program won't compile. I use CODE::BLOCKS.
Screenshot: http://scr.hu/81tw/m6cm0
I really apreciate your help.
Full code below:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int number_normal;
int number_hard;
int guess_normal;
int guess_hard;
int tries_normal=0;
int tries_hard=0;
int mode;
int main()
{
{
cout<<"Choose your mode..."<<endl;
cout<<"Normal (Press 1) or Hard (Press 2)"<<endl;
cin>>mode;
if(mode=1)
cout<<"Normal mode chosen."<<endl;
goto normal;
if(mode=2)
cout<<"Hard mode chosen!"<<endl;
goto hard;
return 0;
}
{
hard:
cout<<"I chose a random number in a range from 1 to 100, can you guess it?"<<endl;
srand(time(NULL));
number_hard = rand()%100+1;
while(guess_hard!=number_hard)
tries_hard++;
cout<<"Enter your guess!(Try "<<tries_hard<<"): ";
cin>>guess_hard;
if(guess_hard=number_normal)
cout<<"Respect! You guessed it in "<<tries_hard<<" tries!"<<endl;
}
{
normal:
cout<<"I chose a random number from 1 to 100. I will give you some clues! Try to guess it."<<endl;
srand(time(NULL));
number_normal = rand()%100+1;
while(guess_normal!=number_normal)
tries_normal++;
cout<<"Enter your guess!(Try "<<tries_normal<<"): ";
cin>>guess_normal;
if(guess_normal==number_normal)
cout<<"Congrats! You're lucky. (Won in "<<tries_normal<<" tries!)"<<endl;
if(guess_normal<number_normal)
cout<<"Too low."<<endl;
else if(guess_normal>number_normal)
cout<<"That's too much!"<<endl;
system("pause");
return 0;
}
The code that works is here
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int number_normal;
int number_hard;
int guess_normal;
int guess_hard;
int tries_normal=0;
int tries_hard=0;
int mode;
int main()
{
{
cout<<"Choose your mode..."<<endl;
cout<<"Normal (Press 1) or Hard (Press 2)"<<endl;
cin>>mode;
if(mode=1)
cout<<"Normal mode chosen."<<endl;
goto normal;
if(mode=2)
cout<<"Hard mode chosen!"<<endl;
goto hard;
return 0;
}
{
hard:
cout<<"I chose a random number in a range from 1 to 100, can you guess it?"<<endl;
srand(time(NULL));
number_hard = rand()%100+1;
while(guess_hard!=number_hard)
{
tries_hard++;
cout<<"Enter your guess!(Try "<<tries_hard<<"): ";
cin>>guess_hard;
if(guess_hard==number_normal)
cout<<"Respect! You guessed it in "<<tries_hard<<" tries!"<<endl;
}
}
{
normal:
cout<<"I chose a random number from 1 to 100. I will give you some clues! Try to guess it."<<endl;
srand(time(NULL));
number_normal = rand()%100+1;
while(guess_normal!=number_normal)
{
tries_normal++;
cout<<"Enter your guess!(Try "<<tries_normal<<"): ";
cin>>guess_normal;
if(guess_normal==number_normal)
cout<<"Congrats! You're lucky. (Won in "<<tries_normal<<" tries!)"<<endl;
if(guess_normal<number_normal)
cout<<"Too low."<<endl;
else if(guess_normal>number_normal)
cout<<"That's too much!"<<endl;
//system("pause");
}
}
return 0;
}
Well, you didn't used braces across your while loops, and as #cowls suggested, there was a closing brace missing after main. Everything else was fine. Also you used a = for comparison between to variables, instead of ==, = is a assignment operator, while == is used for comparison.
You are missing a close brace at the end } that will close your main method.
I would also pay attention to the comments against the question addressing the other issues in your code.
Note: this could not be seen from the screenshot, showing why that was a bad format to post your code in.

My program crashes when calling a function in c++

so i have to make three functions.One asks for how many employees are in a company.The other asks how many days they missed.The third one calculates the average by dividing the amount of employees by the number of days missing.In main,all i have to do is have cout prompts and call the functions.Im not to sure if i'm doing it right,but it crashes when it has to calculate the average.
#include <iostream>
#include <iomanip>
using namespace std;
int employee(int employeeNum);
int missingDays(int daysMissing);
double getAvg(int employeeNum,int daysMissing,double average);
int employee(int employeeNum)
{
cout<<"Enter the number of employee in the company.";
cin>>employeeNum;
return employeeNum;
}
int missingDays(int daysMissing)
{
cout<<"Enter the amount of days employees missed during the past year.";
cin>>daysMissing;
return daysMissing;
}
double getAvg(int employeeNum,int daysMissing,double average)
{
average=employeeNum/daysMissing;
return average;
}
int main()
{
int employeeNum,people,missing,daysMissing;
double avg,average;
people=employee(employeeNum);
cout<<"The number of employees in the company is "<<people<<"."<<endl;
missing=missingDays(daysMissing);
cout<<"The number of days employees missed during the past year is "<<missing<<".";
avg=getAvg(employeeNum,daysMissing,average);
cout<<average;
}
Let me know what i got to do and thanks for the help.
This looks like homework, so you should only expect nudges. So, some nudges: why do your functions employee() and missingDays() take arguments? And why does getAvg() take 3? In which variables do your input values end up? Where are they used next (if at all)?
Your problem is this line
missing=missingDays(daysMissing);
for some reason you have two variables for "daysMissing" (I'm not sure why you pass it in to your missingDays function in the first place)
After that line, missing will contain the value input, not daysMissing (since it's not passed by reference)
Your getAvg function, presumably, is crashing with a division by zero error.
So depending on compiler the value of daysMissing is either undefined or initialized with 0.
In your function getAvg you divide employeeNum/daysMissing;
But you are not allowed to divide by zero, thats's it :)
#include <iostream>
#include <iomanip>
using namespace std;
int employee(int employeeNum);
int missingDays(int daysMissing);
double getAvg(int employeeNum,int daysMissing,double average);
int employee(int employeeNum)
{
cout<<"Enter the number of employee in the company: ";
cin>>employeeNum;
return employeeNum;
}
int missingDays(int daysMissing)
{
cout<<"Enter the amount of days employees missed during the past year: ";
cin>>daysMissing;
return daysMissing;
}
double getAvg(int employeeNum,int daysMissing)
{
if(daysMissing == 0)
{
return 0;
}
return (double)employeeNum/daysMissing;;
}
int main()
{
int employeeNum,people,missing,daysMissing;
double avg,average;
people=employee(employeeNum);
cout<<"The number of employees in the company is: "<<people<<"\n";
missing=missingDays(daysMissing);
cout<<"The number of days employees missed during the past year is: "<<missing<<"\n";
avg=getAvg(people,missing);
cout<<avg;
}

trying to create a dice game using function c++

i am trying to have a function determine the result
a. If the numbers add up to 5, 7, or 12, then the player wins, and the function should return an indication of this (use some integer to represent a win).
b. If the numbers add up to 2, 4, or 11, then the player loses, and the function should return an indication of this (once again, use an integer).
c. If the numbers add up to anything else, then the game is a draw and the function should say this (by way of an integer).
question, do i need a different func for winner, loser, and draw?
and what how can i return a integer to main to let main know that if we have a winner a loser a draw.
just learning to program any help would be greatly appreciated
//function
int outcome(int, int)
{
int die1;
int die2;
int winner;
int loser;
int draw;
if (die1&&die2==5||7||12)
return 99;
if (die1&&die2==2||4||11)
return loser;
else
return draw;
}
// func to get a random number
int rollDice()
{
int roll;
roll = (rand()%6)+1;
return roll;
}
the main func
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
double die1=0;
double die2=0;
int winner=0; //counter for winners
int loser=0; //counter for losers
int draw=0; //counter for draw
//func to determine the outcome
int outcome(int, int);
//func for random numbers
int rollDice();
int outcome(int, int)
if (return==99)
cout <<"winner";
Your code has several syntax errors. If I want to, say, make a function to add two integer numbers, I'd do something like this:
int add(int a, int b) //VARIABLES MUST CARRY A NAME!
{
return a+b;
}
If you want to work with conditions, do this:
if(a==5 && b==6 || a==6 && b==7) //Just as an example
Your fixed condition would be this:
if (die1+die2==5 || die1+die2==7 || die1+die2==12)
Also, study variable scope. Let's say I have the following:
int main()
{
int myVar = 1;
}
int anotherFunction()
{
println("%d", myVar); //This will cause an error, because myVar doesn't exist here, it only exists in main()
}
These are the most notable errors I can see in your code.