C++ strange output when adding integers or doubles together - c++

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.

Related

Different Outputs of an Atoi Converted String-> int

Here is my input file:
Plain Egg
1.45
Bacon and Egg
2.45
Muffin
0.99
French Toast
1.99
Fruit Basket
2.49
Cereal
0.69
Coffee
0.50
Tea
0.75
This is my code. I'm having no problem when people order 8 or 9 items, but as soon as they enter 10 or more items, I get really weird results and not the nicely printed check that I would like to see. For instance, let's say someone orders 8 items and they input "12345678" for their order. I get this:
But if the user inputs that they want let's say 15 items and they order "123456781234567", I get THIS:
Even when they order 10 items, I get just a blank check :/ :
What in the world is happening with my program? Does it have to do with me using c-strings? I want to understand what is going on inside my little computer and understand the way my computer thinks. If you can explain me this in a very simple way (I'm really new so I need something very explanatory with definitions of your fancy words) and some way I can understand, because like I said, I'm really new to computer science. Thank you.
// Local Restaurant: The 5,000 Fed
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
struct menuItemType {
string menuItem;
double menuPrice;
};
void getData(menuItemType list[]);
string showMenu(menuItemType list[]);
void printCheck(string y, menuItemType list[]);
int main() {
string y;
menuItemType menuList[8];
cout << "Hello and welcome to the 5,000 fed. Your local Long Beach café, "
"whose name is inspired by Jesus' miraculous manifestation "
"of bread to feed the 5k! His disciples helped him in passing out "
"the bread, and so I am here, your waiter, to help you and assist "
"you with your order. ";
getData(menuList);
y = showMenu(menuList);
printCheck(y, menuList);
return 0;
}
void getData(menuItemType list[]) {
string menupricet[8];
ifstream inFile;
inFile.open("menudata.txt");
for (int i = 0; i < 8; i++) {
getline(inFile, list[i].menuItem);
getline(inFile, menupricet[i]);
}
for (int i = 0; i < 8; i++) {
list[i].menuPrice = atof(menupricet[i].c_str());
}
}
string showMenu(menuItemType list[]) {
int amount;
char number;
string reps;
string response = "y";
string total = "";
cout << fixed << setprecision(2);
cout << endl << endl;
cout << "Here is our wonderful menu. I do recommend the french toast, "
"similar to the bread that Jesus ate."
<< endl
<< endl;
for (int i = 0; i < 8; i++) {
cout << i + 1 << ". " << setw(13) << left << list[i].menuItem << setw(8)
<< right << list[i].menuPrice << endl;
}
cout << endl;
cout << "How to order: Write the number you would like and specify how many "
"you want of that item by typing it in multiple times. For instance "
"an input of \"1135777\" means that you want two plain eggs, one "
"muffin, one fruit basket, and three coffees."
<< endl
<< endl;
cout << "How many items are you ordering total?: ";
cin >> amount;
cout << endl;
cout << "Please input your order, and press enter after your order: ";
for (int i = 0; i < amount; i++) {
cin >> number;
total += number;
}
return total;
}
void printCheck(string y, menuItemType list[]) {
int k = 0;
int temp = 0;
double bill = 0;
int newone = 0;
k = atoi(y.c_str());
while (k != 0) {
newone = newone * 10;
newone = newone + k % 10;
k = k / 10;
}
cout << "Thank you for dining at the 5,000 fed. Here's your check:" << endl
<< endl
<< endl;
cout << "_________________" << endl;
while (newone > 0) {
temp = newone % 10;
newone /= 10;
bill += list[temp - 1].menuPrice;
cout << left << setw(15) << list[temp - 1].menuItem << right << setw(5)
<< "|" << list[temp - 1].menuPrice << endl;
}
cout << fixed << setprecision(2);
cout << left << setw(15) << "Amount Due:" << right << setw(10) << "|" << bill
<< endl
<< endl;
}
EDIT:
So someone asked me to paste the output as text instead of images so here are the three outputs:
They order 8 items such as "12345678":
_________________
Plain Egg |1.45
Bacon and Egg |2.45
Muffin |0.99
French Toast |1.99
Fruit Basket |2.49
Cereal |0.69
Coffee |0.50
Tea |0.75
Amount Due: |11.31
They order 15 items such as "123456781234567":
_________________
French Toast |1.99
\365\277\357\376^ޝ-
YW\300\365\277\357\376all\377
\200\367\277\357\376
\370\277\357\376
\227\370\277\357\376
\331\370\277\357\376%\371\277\357\376\262
|0.00
Coffee |0.50
Muffin |0.99
\362\277\357\376x\362\277\357\376x\362\277\357\376x\362\277\357\376Plain Egg33333 |0.00
Plain Egg |1.45
Cereal |0.69
\365\277\357\376^ޝ-YW\300\365\277\357\376all\377\200\367\277\357\376\370\277\357\376\227\370\277\357\376\331\370\277\357\376%\371\277\357\376\262 |0.00
Cereal |0.69
Amount Due: |6.31
They order 10 items such as "1234567812":
_________________
Amount Due: |0.00
The problem in your code is associated with the size of the type int. Here is the solution, you may declare k and new one as unsigned long int so that they can hold up to 4,294,967,295 which still contains only 10 orders.
As a solution, you can use the string y as it is instead of converting to int. So that you can place as many orders as you wish. To traverse through the orders, you can use substr and length function of the string.
Let me re-write the printCheck function for, if I may
void printCheck(string y, menuItemType list[]) {
double bill = 0;
for(int i = 0; i< y.length(); i++)
{
string a = y.substr(i, 1);
int kk = atoi(a.c_str());
bill += list[kk - 1].menuPrice;
cout << left << setw(15) << list[kk - 1].menuItem << right << setw(5)
<< "|" << list[kk - 1].menuPrice << endl;
}
cout << fixed << setprecision(2);
cout << left << setw(15) << "Amount Due:" << right << setw(10) << "|" << bill << endl;
}
I hop this helps. Regards.

How do i tell my app "stop running" after set amount rounds?

So i'm making a turn based dice game that's modeled after this game called "underground chinchiro" which was taken from an anime called "Kaiju". I need to set a limit to my program so that it only runs for a set number of rounds,
I'm only a beginner in coding so sorry for anything unusual you see in my code.
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
void roll_3_dice(int &dice1, int &dice2, int &dice3)
{
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
dice3 = rand() % 6 + 1;
return;
}
int main()
{
int cash = 90000;
int wager;
int r;
//dealer's die
int dealer1;
int dealer2;
int dealer3;
// your die
int mdice1;
int mdice2;
int mdice3;
for (int i = 0; i < 10; i++)
{
cout << "Wager up boy!"<< endl;
cin >> wager;
while (wager < 100 || wager > 90000)
{
cout << "Minimum wager is 100; Maximum wager is 90000 ";
cin >> wager;
}
cout << "You wagered: " << wager << endl;
cout << "You have " << cash - wager << " remaining" << endl;
cash = cash - wager;
cout << endl;
cout << "Dealer will now roll the dice" << endl;
roll_3_dice(dealer1, dealer2, dealer3);
cout << "Dealer rolled the following: " << endl;
cout << dealer1 << "-" << dealer2 << "-" << dealer3 << endl;
cout << "It's your turn to roll the dice." << endl;
cout << endl;
cout << "Press any key to roll the dice" << endl;
cin >> r;
roll_3_dice(mdice1, mdice2, mdice3);
cout << "You rolled the following: " << endl;
cout << mdice1 << "-" << mdice2 << "-" << mdice3 << endl;
system ("pause");
}
}
Take a look at for loops. For loops will allow you to run your code for a set number iteration.
e.g. iterate over some code 7 times.
int number_of_iterations = 7;
for(int i = 0; i < number_of_iterations; i++) {
// Your code that you would like to iterate over goes here.
}
EDIT:
As has been specified by the OP (in comments below), the issue is appears to be with the program not stopping to receive input from the user through each iteration of the for loop.
This could be for a number of reasons. My best guess would be that the stdin buffer is not clear and that std::cin continues to read in from the buffer. This could be solver by calling cin.clear() before reading in your input.
is time to learn how to use constants...
define one doing
const int max_round = 5;
and the do a while so long round is <= than max_round
Your problem is pretty unclear. Edit your code, find the section where problems occurring and paste that part only.
like:
while(cin>>wager)
{
if(condition fails)
{
break;
}
}

C++ array structures

I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.
You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link

finding the average of sums made in a loop in c++

Hello everyone I'm trying to find the average of a random amount of numbers that are input into a loop. For sum reason after the loop im able to print the right total, but when i try to find the average i get a weird answer. can anyone help me with this or direct to a thread on here that could help? I wasnt able to find anything on here.
here is my code for the program that isnt working.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inData;
string golferFile;
string golfer;
int matches;
int score;
cout << endl;
cout << "Enter the golfer's filename: ";
cin >> golferFile;
inData.open(golferFile.c_str());
getline(inData, golfer);
inData >> matches;
cout << endl;
cout << "The golfer " << golfer << " has " << matches << " matches with scores"
" of" << endl;
cout << endl;
int count;
count = 1;
int matchNumber;
matchNumber = 1;
int sum;
while(count <= matches)
{
inData >> score;
cout << "Match " << matchNumber << ": " << score << endl;
matchNumber++;
count++;
sum = sum + score;
}
}
int mean;
mean = sum / matches;
cout << "The mean score is " << mean << endl;
return 0;
}
the output i receive is this for the mean
The mean score is 1399255
I found several error in your code.
you forget to initialize your sum variable.
in while loop an extra brace found.remove it
you didn't write anything to stop your loop.that why your loop run infinite time.so initialize you loop also.

Constant variable multiplied with user input

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;