除了函数“tipConvert(tip)”之外,这里的一切都按照我想要的方式工作。
我希望它将数字(例如 15)更改为 0.15,这是百分比的十进制表示形式。
#include <stdio.h>
float tipConvert(int tip);
int main()
{
char value;
int intValue tip;
float bill, result;
intValue = 1;
while(intValue == 1)
{
printf("Would you like to calculate a tip: y or n?\n");
scanf("%s", &value);
if(value == 'y')
{
printf("Enter the bill amount:\n");
scanf("%f", &bill);
printf("Enter the tip amount as an integer:\n");
scanf("%i", &tip);
result = tipConvert(tip)*bill;
printf("Tip for %.2f is %.2f\n", bill,result);
}
else if(value == 'n')
{
printf("Thank you for using Tip Calculator.");
break;
}
else
printf("Please select y or n.\n");
}
return 0;
}
float tipConvert(int tip)
{
return tip / 100;
}
最佳答案
问题是, int 不能存储任何十进制数,并且当调用tip/100时,编译器将其视为整数除法并返回一个 int (在您的示例中为 0),然后将其转换为 float 。
告诉编译器使用浮点除法的最简单方法是使用 100.0f 除以浮点文字而不是整型文字。这应该可以解决这个问题。
或者,您可以先施放尖端以使其漂浮。
关于c - 小费计算——将一个数字换成小数表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42474749/