You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现HackerRank餐费计算任务出现编译警告问题求助

问题原因与修复方案
  • 第一个警告format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’产生原因:
    C语言scanf函数的格式符中,%f仅适配float*类型的指针参数,你声明的mealc是double类型,对应的输入格式符需要替换为%lf。
  • 第二个警告format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’产生原因:
    math.h头文件中的round()函数返回值为double类型,而printf的%d格式符要求传入int类型参数,需要将round(mealc)的结果强制转换为int类型后再打印。
  • 此外代码还存在两处会导致编译失败/运行结果错误的问题:
    1. 读取tip的scanf格式串遗漏了前缀%,错误写成"d",正确写法为"%d",否则无法正常读取小费数值
    2. 总费用计算行存在多余的右括号:mealc = mealc+(mealc*tip/100))+(mealc*tax/100);中第一个运算项后多了一个闭合括号,会触发语法错误

修复后可正常运行的代码

#include <stdio.h>
#include <math.h>
int main()
{
    int tax,tip;
    double mealc;
    
    scanf("%lf",&mealc);
    scanf("%d",&tip);
    scanf("%d",&tax);
    mealc = mealc + (mealc * tip / 100) + (mealc * tax / 100);
    printf("%d", (int)round(mealc));

    return 0;
}

内容的提问来源于stack exchange,提问作者Cyclone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:15:03