Search code examples
c++operation

Getting very strange results when I try to add multiple products


I'm taking my first C++ class in college so I'm a total newbie here. I'm trying to make a program that prompts the user to input a number of Dimes, Nickels, and quarters. Then, the program will take those values, multiply them to the values of the coins themselves, then find the total sum of cents. Lastly, the program will printout the total sum.

However, I'm getting some extremely funky results. For instance, if the user inputs 1 2 3, which will be 1 quarter, 2 dimes, and 3 nickels, they will get a total sum of 1969559999 cents. What on earth am I doing wrong?

using namespace std;
int main(){

    // The number of coins that the user will input
    int quarters;
    int dimes;
    int nickels;

    // Coin values 
    int quarters_value = 25;
    int dimes_value = 10;
    int nickels_value = 5;

    // Multiplier 
    int quarter_product = quarters * quarters_value;
    int dime_product = dimes * dimes_value;
    int nickel_product = nickels * nickels_value;

    //Final sum 
    int final_sum = quarter_product + dime_product + nickel_product;
 
    cout << "Enter quarters, dimes, and nickels: \n";
    cin >> quarters >> dimes >> nickels;
    cout << "Number of quarters: " << quarters << endl;
    cout << "Number of Dimes: " << dimes << endl;
    cout << "Number of Nickels: " << nickels << endl;
    cout << "Quarter Product is: " << quarters_value << endl;
    cout << "Dime Product is is: " << dime_product << endl;
    cout << "Nickle Product is: " << nickel_product << endl;
    cout <<  "The amount is " << final_sum << endl;
  


    return 0;
} 

Solution

  • Variables do not work the way you assume. When you do:

    int quarters;
    int quarters_value = 25;
    int quarter_product = quarters * quarters_value;
    cin >> quarters;
    

    Everything goes from top to bottom. It means that once you input a value for quarters (cin >> quarters), variable quarter_product has already been assigned. Changing quarters does not change quarter_product.

    By doing:

    int quarter_product = quarters * quarters_value;
    

    you are not creating a mathematical rule that quarter_product will always be equal to the product of the quarters and quarters_value variables. What you are doing is simply taking the current value of quarters and quarter_value, computing their product and assigning it.

    Given the fact that quarters has not been assigned a value, this results in Undefined Behavior. Anything can happen.

    To fix things, you need to first read the user input into the variable, and compute the product afterwards:

    int quarters;
    int quarters_value = 25;
    cin >> quarters; // first
    int quarter_product = quarters * quarters_value; // second
    int final_sum = quarter_product + dime_product + nickel_product; // third
    cout <<  "The amount is " << final_sum << endl; // fourth