I've been trying to create a simple program that allows me to display a total score after the user has entered the ammount of successful hits, totalHits, by multiplying that input with the constant variable POINTS resulting in another variable; score.
I didn't think creating such a program would be any problem, but as usual, I was wrong.. When I run the program score is always random, even if I enter '1' as totalHits every time. It can differ from 444949349 to -11189181 to name a couple of examples. I have no idea what I've done wrong, so it would be great if someone could give me a clue as to what to do next :)
Here's the code:
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
int score = totalHits * POINTS;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}
Big thanks to KerrekSB and Paddyd for providing me with the correct answer. Here's the finished code with comments:
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
/*As you can see I moved the line below from the top of the code.
The problem was I had not properly learned how C++ executes the code.
The orignal code was written in a way that calculates `score` before
the user could decide it's value, resulting in a different total score than
it should have been. In the finished code, the user inputs what
value `totalHits` is, THEN score is calculated by using that value. */
int score = totalHits * POINTS;
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}
int totalHits;
int score = totalHits * POINTS;
You are multiplying by an uninitialized variable (totalHits)! You need to apply a value to totalHits before doing this calculation.
Try using the code like this:
const int POINTS = 50;
int totalHits;
int score;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
score = totalHits * POINTS; //totalHits has a value here
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
Related
at the moment I'm trying to add up the numbers for my hand and the hit cards, the issue is I created a function for my random number generator so that I can keep calling it into my dice game and the blackjack game, I would normally add the number generator to a variable and call it a day but I made it into a function instead. I am still new to c++.
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
void RandomNumber() { cout << (rand() % 10) + 1; }
void blackjack(int total) {
int startstakes = 15;
int stakes;
int hand;
cout << "Welcome to the Blackjack(21) table\n"
<< "How much are you adding to your initial 15 chip stake - ";
cin >> stakes;
cout << "New stake - " << stakes + 15 << " remaining chips - "
<< total - (stakes + 15) << endl;
cout << "Here is your hand - ";
RandomNumber();
cout << " and ";
RandomNumber();
cout << "Hit me cards: 0 - 0 - 0\n"
<< "Total = ";
system("pause>0");
}
int main() {
int total = 0;
int choice;
srand((unsigned)time(NULL));
cout << "Welcome to Royal Casino!!!, How much money do you wish to "
"convert? ";
cin >> total;
cout << "Excelent you currently have " << total << " Chips.\n"
<< "Let's Begin!\n\n"
<< "We have to tables available today\n";
cout << "1) Blackjack (21)\n"
<< "2) Dice\n"
<< "Both have an entry fee of 15 Chips\n"
<< "Select a table - ";
cin >> choice;
if (choice == 1) {
blackjack(total);
}
if (choice == 2) {
dice();
}
system("pause");
}
So the issue is that you should return the value instead of printing it. Like this (note the return type has changed from void to int)
int RandomNumber() {
return (rand() % 10) + 1;
}
A function which returns a value is much more flexible than a function which prints a value.
Now you can use a function call RandomNumber() pretty much the same way as a variable. E.g.
cout << RandomNumber() << " and " << RandomNumber();
or
int var = RandomNumber();
So the code as is will run, however the calculations for the total and average variable are calculated when the firstE-fourthE variables are equal to 0. Surely there is a way to redefine them later in the code or recalculate them? I apologize for the horrible formatting and indents, this site is very picky.
#include <iostream>
using namespace std;
int main()
{
char fi = '\0', mi = '\0', li = '\0', end = '\0';
float firstE = 0,
secondE = 0,
thirdE = 0,
fourthE = 0,
total = firstE + secondE + thirdE + fourthE,
average = total / 4;
cout << "This program will calculate the average of a student's exam grades." << endl;
cout << "Please enter the first initial of the student's name: ";
cin >> fi;
cout << "Please enter the middle initial of the student's name: ";
cin >> mi;
cout << "Please enter the last initial of the student's name: ";
cin >> li;
cout << "Please enter the student's first exam score: ";
cin >> firstE;
cout << "Please enter the student's second exam score: ";
cin >> secondE;
cout << "Please enter the student's third exam score: ";
cin >> thirdE;
cout << "Please enter the student's fourth exam score: ";
cin >> fourthE;
/*float total = firstE + secondE + thirdE + fourthE,
average = total / 4;*/
cout << "Student's initials: " << fi << mi << li << endl;
cout << "Exam 1: " << firstE << endl;
cout << "Exam 2: " << secondE << endl;
cout << "Exam 3: " << thirdE << endl;
cout << "Exam 4: " << fourthE << endl;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
cin >> end;
}
Why are you doing the calculations BEFORE you've even got values to do the calculations with? Your code sequence should be:
1. define variables
2. get input from user
3. do calculations
4. present results
You're trying to eat your cake before you've even gone to the store to buy the eggs/milk/sugar, let alone mixing/baking it.
To get the desired behaviour from your code, you need to calculate the total and average after your inputs have been populated. Assuming that the grades are whole values, you can use ints to store each exam result:
#include <iostream>
int main()
{
char fi = '\0', mi = '\0', li = '\0', end = '\0';
int firstE = 0,
secondE = 0,
thirdE = 0,
fourthE = 0,
/*IO*/
float average = (firstE + secondE + thirdE + fourthE)/4;
/*IO*/
return 0;
}
This will provide you with working code.
We can clean it up further though. Why would we not be able to store John Edward Smith's initials as "JES" instead of inputting each character seperately?
#include <iostream>
#include <string>
int main()
{
std::string student_initials;
int firstE = 0,
secondE = 0,
thirdE = 0,
fourthE = 0,
std::cout << "This program will calculate the average of a student's exam grades." << endl;
std::cout << "Please enter the student's initials: ";
std::cin >> student_initials;
/*MORE IO*/
float average = (firstE + secondE + thirdE + fourthE)/4;
std::cout << "Student's initials: " << student_initials << std::endl;
/*MORE IO*/
return 0;
}
That's better, the interface to the user is a bit simpler. But what if a student took an extra exam? What if they only took 3? Either you can't input all their results, or the maths is wrong.
We can introduce a loop to the code that can handle the input of the results:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
/* STUFF */
int total;
int exam_result;
int exam_count = 1;
string input;
//this loop will capture multiple exam results (safely)
do
{
std::cout << "Please enter the results of exam #" << exam_count \
<< "\nleave blank if all results have been entered" << std::endl;
std::getline (std::cin, input);
stringstream(input) >> exam_result;
if (exam_result)
{
total += exam_result;
exam_count++;
}
} while (exam_result);
float average = total/exam_count;
/* STUFF */
return 0;
}
this captures multiple exam results (and totals and counts them) using a safe method of handling cin
It does however prevent you from printing out each individual result before the average but you can store them in a std::vector and iterate through them to do that. I'll leave that up to you.
Final code:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string student_initials;
std::cout << "This program will calculate the average of a student's exam grades." << endl;
std::cout << "Please enter the student's initials: ";
std::cin >> student_initials;
int total;
int exam_result;
int exam_count = 1;
string input;
//this loop will capture multiple exam results (safely)
do
{
std::cout << "Please enter the results of exam #" << exam_count \
<< "\nleave blank if all results have been entered" << std::endl;
std::getline (std::cin, input);
stringstream(input) >> exam_result;
if (exam_result)
{
total += exam_result;
exam_count++;
}
} while (exam_result);
float average = total/exam_count;
std::cout << "Student's initials: " << student_initials << std::endl;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
return 0;
}
How do I define a variable or recalculate it later in the code?
Like this
#include <iostream>
int main()
{
int a; // define it once
int b; // define it once
int c; // define it once
int total; // define it once
a = 2; // change its value
b = 4;
c = 1;
total = a + b + c; // or calculate its value
std::cout << "total: " << total << '\n';
a = 9; // change its value AGAIN
b = 1;
c = 12;
total = a + b + c; // and calculate its value AGAIN
std::cout << "total: " << total << '\n';
}
I'm attempting to create a program to figure out Delta-V for my Kerbal Space Program game, and C++ (being run in the Eclipse IDE) does not allow for use of log() without assuming I'm trying to call a function. Thank you so much for help! It's really nice of you.`
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout << "Hello. Welcome to the Kerbal Space Program Delta V Calculator. \n";
cout << " \n";
cout << "Note that each stage must use the same engine for this calculator.";
cout << "\n";
cout << "\nHow many stages make up your rocket? :";
int stageNumber;
cin >> stageNumber;
//cout << "Your rocket has " << stageNumber << " stages.\n";
cout << "\n\nStart from the bottom stage, please. ";
//ACTUAL DELTA V CALCULATIONS
for(int currentStage = 1; currentStage <= stageNumber; currentStage = currentStage + 1){
cout << "What is the total mass of this stage? :";
int totalMass;
cin >> totalMass;
cout << "What is the fuel mass of this stage? :";
int fuelMass;
cin >> fuelMass;
cout << "\n";
int dryMass;
dryMass = totalMass - fuelMass;
cout << "Your dry mass is" << dryMass << "\n";
cout << "\n";
cout << "Give the specific impulse of this stage's engine. \n";
int iSP;
cin >> iSP;
cout << "Here is the Delta V of your rocket.\n";
int deltaMass;
deltaMass = totalMass/dryMass;
int deltaV;
deltaV = iSP * log(deltaMass);
cout << deltaMass
exit(0);
}
}
`
log() is a function in the C standard library that takes the natural logarithm of a number. The name is effectively reserved — pick something else.
I need help with a program for school. We had to write a program that asks the user for information about a baseball player. We need to calculate the players batting average with their games played, number of times at bat and number of hits. I am running into an issue where my computation for the average is outputting a set number and not performing any computations. I am entering whole integers for all the variables that are used for calculation. So i would input numbers like 1, 4 , 10 etc... As the program stands the value my formula is setting itself equal to is 15903.876. All of my variables used for the average formula are declared as integers and the batting average itself is declared as a double. I have done some debugging my self and found that the computation messes up when it divides the number of times at bat by the number of hits. If anyone could help me figure out the issue i would appreciate it.
//libaries
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class battingAverage
{
public:
string pName;
int nBats;
int tHits;
int gPlayed;
int gcalled;
double average;
double average1;
double playeraverage;
};
int main()
{
string numberPlayers;
int nplayers;
//enters the number of players the user wants to enter data for
cout << "Enter the number of players you want to enter data for: ";
cin >> numberPlayers;
cout << endl;
//converts the value of numberPlayers to nplayers
istringstream convert(numberPlayers);
//sets integer nplayers equal to the value of the string numberPlayers
if(! (istringstream(numberPlayers) >> nplayers) )
{
nplayers = 0;
}
cout << "This program calculates the batting average of baseball players.\nYou may enter data for " << nplayers << " players." << endl;
battingAverage ba[nplayers];
int index = 0;
//while statement to get data
while(index < nplayers)
{
cout << "Enter the players last name: " << endl;
cin >> ba[index].pName;
cout << "Enter the number of games the player played: " << endl;
cin >> ba[index].gPlayed;
cout << ba[index].gPlayed << endl;
cout << "Enter the number of games the player was called in for: " << endl;
cin >> ba[index].gcalled;
cout << ba[index].gcalled << endl;
cout << "Enter the number of times the player was at bat: " << endl;
cin >> ba[index].nBats;
cout << ba[index].nBats << endl;
cout << "Enter the number of time the player hit: " << endl;
cin >> ba[index].tHits;
cout << ba[index].tHits << endl;
if(ba[index].tHits > ba[index].nBats)
{
cout << "Enter a valid value for the number of times the player hit: ";
cin >> ba[index].tHits;
}
cout << endl;
index++;
}
//rounds average to 3 decimal places
cout << fixed << setprecision( 3 );
//average formula
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
cout << ba[index].playeraverage << endl << endl;//just temp line to check calculation of average.
ba[index].average = .000;
ba[index].average1 = .099;
while(ba[index].average < 1 && ba[index].average1 < .899)
{
ba[index].average +=.100;
ba[index].average1 += .1;
//prints chart
cout << setprecision( 1 ) << ba[index].average << "00" << setprecision( 3 ) << setw(12) << ba[index].average1 << endl;
}
cout << "1.000" << setw(12) << "1.000" << endl;
//version of system pause
cout << "\nPress enter to continue...";
cin.sync();
cin.ignore();
return 0;
}
On this line:
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
You have this expression:
(ba[index].nBats / ba[index].tHits)
Because both nBats and tHits are integers, you're using only integer math.
The answer will be an integer.
For example:
nBats = 10 & tHits = 3, you'd expect the expression to be 3.333.
But it would only be 3
To fix this, I recommend changing to:
((double)ba[index].nBats / ba[index].tHits)
Same thing again with the expression about gPlayed and gcalled.
Your value of index is wrong during the calculations.
I found this as soon as I put your code in a debugger and stepped through it, something you really should have done yourself.
You start with int index = 0;, and increment it as the user puts in each player's data.
At the end of the input-loop, index is now the same as the number of players.
(eg. if you had 5 players, index is now 5, and the player data is stored in ba[0], ba[1], ba[2], ba[3], and ba[4])
Note that at this point ba[5] is NOT valid data. But that is exactly where ba[index] is!
You do all your calculations on ba[index], which is invalid data, and you wonder why you get meaningless results?
I recommend you set index back to 0 before starting your calculations, and make another loop that does the necessary calculations for each player 0...4.
Im having a problem with adding numeric types together in c++ and cant figure out why its happening, I expect when I input 3 bowling scores together I will get 9 or 9.00, instead I get something crazy like 3.31748e+258, what am I doing wrong? any help will go a long way thanks!
#include<iostream>
#include<cmath>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
/*Coordinate variables*/
double bowlTotal;
double bowlScore;
const int FIVE_PLAYERS = 5;
for( int players = 0; players < FIVE_PLAYERS ; players++ )
{
cout << "Player " << players + 1 << endl << endl;
for( int games = 0; games < 3; games++ )
{
double score;
score = 0;
cout << "Please enter score for game #" << games + 1<< ": ";
cin >> score;
cout << endl;
bowlTotal += score;
}
cout << endl << endl <<"The final score for player #"<< players + 1 << " = " << bowlTotal << endl << endl;
bowlScore += bowlTotal;
}
cout << endl << endl <<"The final team score = " << bowlScore << endl << endl;
system("PAUSE");
return 0;
}
You need to initialize your variables to 0 before you use them, as shown below.
double bowlTotal = 0.0;
double bowlScore = 0.0;
Typically compiler will not do this for you, and the variables will be filled with effectively garbage values, to which you add your scores.
As GManNickG succinctly puts it, reading an uninitialized variable is undefined behavior.
You did not initialize bowlTotal or bowlScore, so they contain garbage.