请问我这个代码问题在哪?

img


这是c primer plus第五章编程练习第四题,做了很久但是输入身高后就显示出错

输入double类型,用 %lf

【以下回答由 GPT 生成】

这段代码的问题在于scanf_s函数的格式化字符串的写法不正确。

scanf_s函数的格式化字符串中不支持精度修饰符,因此 %.1f会导致输入错误。应该使用%lf作为格式化字符串,因为height是一个double类型的变量。

以下是修改后的代码:

#include<stdio.h>
#define I_PER_CM 2.54

int main(void) {
    int feet = 5;
    double height, inches;
    printf("Please enter a height in centimeters:");
    scanf_s("%lf", &height); // 修改此处的格式化字符串
    while (height > 0) {
        inches = (height - feet * 30.48) / I_PER_CM;
        printf("%.1f cm = %d feet, %.1f inches\n", height, feet, inches);
        printf("Please enter a height in centimeters (<= 0 to quit):");
        scanf_s("%lf", &height); // 修改此处的格式化字符串
    }
    printf("bye");
    return 0;
}

请注意在代码中修改了两处scanf_s函数的参数:"%.1f" 改为 "%lf"。这样修改后,输入身高就不再会显示错误。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^