-2

I need the program to act as a vending machine, keep running total and determine change if applicable.

#include <iostream>
using namespace std;

int main()
{

    cout << "A deep-fried twinkie costs $3.50" << endl;
    double change, n = 0, d = 0, q = 0, D = 0, rTotal = 0;

    do
    {
        cout << "Insert (n)ickel, (d)ime, (q)uarter, or (D)ollar: ";
        cin >> rTotal;
        if (rTotal == n)
            rTotal += 0.05;
        if (rTotal == d)
            rTotal += 0.10;
        if (rTotal == q)
            rTotal += 0.25;
        if (rTotal == D)
            rTotal += 1.00;

         cout << "You've inserted $" << rTotal << endl;


        cout.setf(ios::fixed);
        cout.precision(2);


        } while (rTotal <= 3.5);

        if (rTotal > 3.5)
            change = rTotal - 3.5;


            return 0;
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Comparing floats and doubles : https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison – Bhawan Sep 30 '17 at 15:08
  • You need two different variables for the currently inserted coin, and the total amount. – mkrieger1 Sep 30 '17 at 15:10
  • Also you are currently checking in all cases if the letter that the user has entered is equal to 0 which is never true. – mkrieger1 Sep 30 '17 at 15:14

1 Answers1

0

You are doing a couple things wrong. First, you need to have a variable to read the character of the option (the n, d, q, and D). You also need to use those letters as characters (i.e. 'n' and so on). Then, you need to compare the option you read from the input with the character, not the total inserted. Finally, if the user has inserted $3.50 it wont need to iterate again, so the condition should be rTotal < 3.5.

Here's the code with the corrections:

#include <iostream>
using namespace std;

int main() {
    cout << "A deep-fried twinkie costs $3.50" << endl;
    double change, n = 0, d = 0, q = 0, D = 0, rTotal = 0;
    char op;
    do {
        cout << "Insert (n)ickel, (d)ime, (q)uarter, or (D)ollar: ";
        cin >> op;
        if (op == 'n')
            rTotal += 0.05;
        else if (op == 'd')
            rTotal += 0.10;
        else if (op == 'q')
            rTotal += 0.25;
        else if (op == 'D')
            rTotal += 1.00;
        cout.setf(ios::fixed);
        cout.precision(2);
        cout << "You've inserted $" << rTotal << endl;
    } while (rTotal < 3.5);
    if (rTotal > 3.5)
        change = rTotal - 3.5;
    return 0;
}

If you want to count the coins the user has inserted, then add the brackets to the if statements and add 1 to the corresponding variable if such coin was inserted.