1

我刚开始学习 C++ 编程。我的程序运行完美,但当用户输入 sa 字符并按下回车键时,我还需要关闭它。我不知道应该怎么做。任何帮助将不胜感激。到目前为止,我的代码是(运行良好):

#include <iostream>
using namespace std;

int main()
{
    int money_spent, money_tendered;

    cout << "Enter the total amount spent: \n";
    cin >> money_spent;

    cout << "Enter the amount tendered: \n";
    cin >> money_tendered;

    int balance = money_tendered - money_spent;
    int ten_bills = balance / 1000;
    balance = balance % 1000;
    int five_bills = balance / 500;
    balance = balance % 500;
    int dollar_coins = balance / 100;
    balance = balance % 100;
    int quater_coins = balance / 25;
    balance = balance % 25;
    int dimes = balance / 10;
    balance = balance % 10;
    int nickels = balance / 5;
    balance = balance % 5;
    int pennies = balance;

    cout << " \n \n"
        << "Your change is: \n"
        << ten_bills << " tenn dollar bill(s). \n"
        << five_bills << " five dollar bill(s). \n"
        << dollar_coins << " one dollar coin(s). \n"
        << quater_coins << " quater(s). \n"
        << dimes << " dime(s). \n"
        << nickels << " nickel(s). \n"
        << pennies << " pennie(s). \n";

    return 0;
}
4

4 回答 4

4

添加

cin.ignore();    
cin.get();

return 0;

您需要cin.ignore(), 忽略输入后键入的 ENTER money_tendered。否则,此 ENTER 将被捕获,cin.get()而不是您要输入的最后一个字符。

于 2013-09-19T06:03:29.780 回答
0

Add the following line at the end of your program.

system("pause");

One the application comes to this line it will show you

Press any key to continue . . . message. Once you click a button the application automatically exit the process.

于 2014-07-18T04:47:36.163 回答
0

您需要更改 cin 才能读取字符串。然后您需要检查该字符串是否为“s”。如果是这样,您希望返回 0。否则,您希望将字符串转换为整数并将其存储在 money_spent 或 money_tendered 中。然后你想将整个过程包装在一个 while(1) { } 循环中,这样它就不会自动退出。

于 2013-09-19T06:25:04.473 回答
0

利用

getchar();

这是一个标准的 c 函数。

于 2013-09-19T06:20:32.003 回答