0

所以我试图设置这个程序来计算一个账户的余额。我需要确保将起始余额输入为正数。我有积极的部分,但我如何确保输入也是一个数字而不是字母或其他非数字?

#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;

int main()
{

double  startBal,    // Starting balance of the savings account
        ratePercent, // Annual percentage interest rate on account
        rateAnnual,  // Annual decimal interest rate on account
        rateMonth,   // Monthly decimal interest rate on account
        deposit1,    // First month's deposits
        deposit2,    // Second month's deposits
        deposit3,    // Third month's deposits
        interest1,   // Interest earned after first month
        interest2,   // Interest earned after second month
        interest3,   // Interest earned after third month
        count;       // Count the iterations

// Get the starting balance for the account.
cout << "What is the starting balance of the account?" << endl;
cin >> startBal;
while (startBal < 0 ) {
    cout << "Input must be a positive number. Please enter a valid number." << endl;
    cin >> startBal;
}

// Get the annual percentage rate.
cout << "What is the annual interest rate in percentage form?" << endl;
cin >> ratePercent;

// Calculate the annual decimal rate for the account.
rateAnnual = ratePercent / 100;

// Calculate the monthly decimal rate for the account.
rateMonth = rateAnnual / 12;

while (count = 1; count <= 3; count++)
{

}

return 0;
}

谢谢!!!

4

3 回答 3

4

您可以验证是否cin成功:

double startBal;
while (!(std::cin >> startBal)) {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
    std::cout << "Enter a valid number\n";
}

std::cout << startBal << endl;

不要忘记#include <limits>使用std::numeric_limits<streamsize>::max().

于 2013-10-08T21:36:24.117 回答
1
double x;
std::cout << "Enter a number: ";
std::cin >> x;
while(std::cin.fail())
{
    std::cin.clear();
    std::cin.ignore(numeric_limits<streamsize>::max(),'\n');
    std::cout << "Bad entry.  Enter a NUMBER: ";
    std::cin >> x;
}

xand替换double为您需要的任何变量名称和类型。显然,将您的提示修改为任何必要的内容。

于 2013-10-08T21:34:43.973 回答
0

你所要求的实际上是相当困难的。唯一完全正确的方法是将您的输入读取为字符串,然后查看该字符串的数字格式是否正确,然后才将字符串转换为数字。我认为当你只是一个初学者时,这很困难。

于 2013-10-08T21:45:47.277 回答