c - 小费计算——将一个数字换成小数表示

标签 c input calculation

除了函数“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/

相关文章:

flutter - 如何在flutter中实现Log base 2?

javascript - 将 javascript 计算值传递到数据库是不好的做法吗?

sql - 获取列总和并用于计算总数的百分比,为什么不适用于 CTE

c malloc 分配内存时断言失败

c - 在 C 中,main 不需要是一个函数?

html - 如何使用 CSS 定位文本输入字段?

python - 输入列表中的单个项目

c - 夹板如何知道我的函数没有在另一个文件中使用?

c - 释放指针引用的结构中的指针

php - 禁用输入字段中的 html 标签、php、脚本