gpt4 book ai didi

c - 由于字符串的格式以及所使用的参数,我的 printf 格式说明符将无法编译

转载 作者:行者123 更新时间:2023-11-30 16:31:14 25 4
gpt4 key购买 nike

我正在尝试编写一个小程序,将一个人的高度或任何高度从英制转换为公制,但我收到编译器错误告诉我:“格式字符串不使用数据参数”

    printf("Enter your height with just a space between feet and inches: ");
scanf("%2s", "%f", &ft, &in);
ft = in / 12;
double delta = (ft * 30.48);
double rem = in * 2.54;
double calc = delta + rem;
printf("Your height is %f ft and %.1f in\n", delta, calc);

return (0);

最佳答案

您的代码中有很多错误。

  • ft (英尺)通常是浮点变量,使用 %f而不是%s 。还要在单双引号中给出所有格式说明符,例如 "%f %f" 。也许你想要这样

    scanf("%2f %f", &ft, &in);

  • 您应该检查是否 scanf()通过检查 scanf() 的返回值判断是否成功,通过输入 man 3 scanf 阅读手册页在命令提示符下或参见此处 http://man7.org/linux/man-pages/man3/scanf.3.html 。例如 int ret = scanf("%2f %f", &ft, &in);

这是示例代码

#include<stdio.h>
int main(void) {
float ft = 0, in = 0; /* don't keep uninitialized local variable */
printf("Enter your height with just a space between feet and inches: ");
scanf("%2f %f", &ft, &in);
ft = in / 12;
double delta = (ft * 30.48);
double rem = in * 2.54;
double calc = delta + rem;
printf("Your height is %f ft and %.1f in\n", delta, calc);
return 0;
}

同时使用 -Wall 编译您的程序标记如 gcc -Wall test.c不要忽视警告,解决它们。通过使用 -Wstrict-prototypes -Werror 进行编译,更好地将所有警告视为错误这样就可以减少出现错误的机会。例如

gcc -Wall -Wstrict-prototypes -Werror test.c

终于学会了如何调试一小段代码https://ericlippert.com/2014/03/05/how-to-debug-small-programs/

关于c - 由于字符串的格式以及所使用的参数,我的 printf 格式说明符将无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50731820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com