c - printf 不产生输入值

标签 c printf scanf format-specifiers

我有以下代码块。最后一行旨在生成用户输入的 XYP 值。但它只返回

(0,0,0)

而不是用户给出的值。我错过了什么?

printf("What is the robot's initial X position? (cm)\n");
scanf("%f",&X);
printf("What is the robot's initial Y position? (cm)\n");
scanf("%f",&Y);
printf("What is the robot's initial angular position? (degrees)\n");
scanf("%f",&P);
printf("The initial position is (%d, %d, %d)\n", X,Y,P);

最佳答案

假设XYP的类型为doublefloat (输入部分scanf()),您需要使用%f%lf格式说明符(如需要)打印(或扫描)值。

  • 要打印floatdouble,需要使用%f
  • 扫描float时,使用%f,扫描double时,使用%lf

对特定格式说明符使用错误类型的参数是 undefined behaviour%d 需要一个 int 参数。因此,在您的情况下,使用 %d 作为 floatdouble 类型的参数是 UB。

关于c - printf 不产生输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918889/

相关文章:

PHP fscanf 与 fgets

c - 在 C 中释放结构的函数

c - 存储大基数 B 的最佳方法?

c - printf 在行尾插入 %

c - 将 printf 与 %s 和 char* 一起使用时出现问题

c - scanf 异常与 %c 和 %s 相关行为

c 从文件中读取 float 并排序

c - exit() 会在 _SUCCESS 和 _FAILURE 上释放分配的内存

c - 这个C代码错了吗?

c - Printf 和数组