Reputation: 11
I needed a program where a user orders items but the output was wrong. It was outputting 12-digit numbers when I only needed 2-3 digits. Why is it outputting bigger numbers than expected?
#include <iostream>
using namespace std;
int main()
{
//Order
int Pfries = 80, Pburgers = 150, Pdonuts = 30, Picecream = 25, Psoftdrinks = 20;
int Nfries, Nburgers, Ndonuts, Nicecream, Nsoftdrinks;
int fries = Pfries * Nfries, burgers = Pburgers * Nburgers, donuts = Pdonuts * Ndonuts, icecream =
Picecream * Nicecream, softdrinks = Psoftdrinks * Nsoftdrinks;
string customer;
cout<<"Welcome to Murakani Cafe!"<<endl;
cout<< "Enter the name of the customer: ";
cin>>customer;
cout<< "Enter the number of fries ordered:";
cin>>Nfries;
cout<< "Enter the number of burger(s) ordered: ";
cin>>Nburgers;
cout<< "Enter the number of donut(s) ordered: ";
cin>>Ndonuts;
cout<< "Enter the number of ice cream ordered: ";
cin>>Nicecream;
cout<< "Enter the number of soft drink(s) ordered: ";
cin>>Nsoftdrinks;
//Output
cout<< "Hi "<< customer << "! Here is the summary of your order:"<<endl;
cout<<""<<endl;
cout<< Nfries << " fries "<< Pfries << fries <<endl;
cout<< Nburgers<< " burgers "<< Pburgers << burgers<<endl;
cout<< Ndonuts<< " donuts "<< Pdonuts << donuts<<endl;
cout<< Nicecream<< " ice cream "<< Picecream << icecream<<endl;
cout<< Nsoftdrinks<< " soft drinks "<< Psoftdrinks << softdrinks<<endl;
return 0;
}
Upvotes: 1
Views: 179
Reputation: 88092
In C++ the order you do things matters. This is OK
int Pfries = 80;
cout<< "Enter the number of fries ordered:";
cin>>Nfries;
int fries = Pfries * Nfries;
because at the point where you calculate fries
both Pfries
and Nfries
have values.
But this (which is what you do) is not OK
int Pfries = 80;
int fries = Pfries * Nfries;
cout<< "Enter the number of fries ordered:";
cin>>Nfries;
In this calculation you use the Nfries
variable before it has been given a value. This is technically known as undefined behaviour, which is another way of saying that the effects of this code are unpredictable.
What you seem to be thinking is that you've written a formula fries = Pfries * Nfries
and C++ will recalculate that formula if any of the variables get different values. But that's not how C++ (or most programming languages) work. Instead your program is a sequence of statements which get executed in a given order, and the values used are the values that the variables have at the time when the given statement is executed.
Upvotes: 1