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类型后再打印。 - 此外代码还存在两处会导致编译失败/运行结果错误的问题:
- 读取
tip的scanf格式串遗漏了前缀%,错误写成"d",正确写法为"%d",否则无法正常读取小费数值 - 总费用计算行存在多余的右括号:
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
相关产品推荐
相关产品推荐

