【问题标题】:How to print a float being the decimal place's value a variable, in C [duplicate]如何在C中打印作为小数位值的浮点数变量[重复]
【发布时间】:2020-04-10 23:07:48
【问题描述】:

我想使用带有输入值的变量作为 C 中的小数位数。 我使用的 IDE 是 Windows 中的 CodeBlocks。 这是我尝试制作的代码示例(这是一个示例):

#include <stdio.h>
int main()
{
    int value;
    float number;
    printf("Enter a number (float).\n");
    scanf("%f", &number);
    printf("Enter a value.\n");
    scanf("%d", &value); 

    // here I'm trying to use the input value (float number) with the decimal places value (int value). 
    // In %.%df I'm trying to use the variable int value as the decimal places number
    // (example: %.2f, being 2 the decimal places number) even though it is an int variable.
    printf("The number %f with %d decimal places is %.%df.\n", 
        number, value, number, value); 

    return 0;
}

【问题讨论】:

  • 你有什么问题?

标签: c


【解决方案1】:

使用* 表示精度:

printf("The number %f with %d decimal places is %.*f.\n", number, value, value, number); 

【讨论】:

  • .*:精度未在格式字符串中指定,而是作为附加的整数值参数必须格式化的参数之前指定。所以value需要先走。
  • 是的。我只是复制/粘贴了 OP 的代码而不检查它。由于 va_arg 在我的机器上的行为,它在我的快速测试中对我有用。修复!
  • "%.*f" 中的* 不是宽度。它是精度
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2021-05-15
  • 2011-02-02
  • 2021-05-07
相关资源
最近更新 更多