我正在为一个学校项目编写一个简单的税收计算器程序,但是我遇到了一些输入验证问题,需要帮助。我需要执行检查以验证输入是整数还是浮点数。输入内容不能包含任何符号,输入内容不能包含负整数或浮点数。我的代码在下面列出。
我尝试了各种while和if语句。我一直在Internet上进行搜索,但没有找到实现此目的的优雅方法。另外,无论出于何种原因,如果我在当前代码版本中使用while语句输入符号,它将永远循环,并且永远不会提示我输入新数字。
#include <stdio.h>
int main()
{
float fPrice;
float fTax=0.0f;
float fFinalPrice;
int dividend;
int iPrice;
//int iFinalPrice;
float fInput;
int x;
double dTax;
dividend = 100;
printf("Enter sales tax rate as a whole number (e.g. 1, 6, 8, 10): ");
scanf("%lf", &dTax);
while((dTax < 1.0) && (dTax != (int)dTax))
{
printf("ERROR: Invalid input received.\n");
printf("Enter sales tax rate as a whole number (e.g. 1, 6, 8, 10): ");
scanf("%lf", &dTax);
}
fTax = dTax/dividend;
//printf("\nThe converted Tax Rate: %.2f\n", fTax);
printf("Enter cost (e.g. 10.43 or 10: ");
scanf("%f", &fPrice); // set price input to a float var.
while((fPrice < 1.0) && (fPrice != (int)fPrice))
{
printf("ERROR: Invalid input received.\n");
printf("Enter cost (e.g. 10.43 or 10: ");
scanf("%ff", &fPrice);
}
iPrice=fPrice; // take the float and assign it to the int var. The int var will always be a whole number regardless of what value is passed in.
if(iPrice==fPrice) // look at int var and if == to float var then the value can be considered to be an integer.
{
fFinalPrice = iPrice + (iPrice*fTax);
printf("Price with tax is $%.2f", fFinalPrice);
}
else // price is a float
{
fFinalPrice = fPrice + (fPrice*fTax);
printf("Price with tax is $%.2f", fFinalPrice);
}
return 0;
}