错误的计算? C编程初学者

时间:2017-08-30 19:06:49

标签: c

我通过指南学习c,我很享受。 但是,有一个问题我被困住了。

问题是:

"编写一个程序,在编写数字" x"和数字" y",程序显示x中x的百分比。"

"当x = 54且y = 84"

时,答案应为64%

显然,54/84 = 0.64 ...... * 100,约为64%。 但是,当我运行我的程序时,它显示84.689699。 我没有使用" * 100"但没什么。它显示0.84689699 ......

我的程序是错误的还是编译器的问题? 我是初学者,如果有人告诉我什么是错的,那将会非常有帮助。

PS:我使用atom.io和gcc-compiler

#include <stdio.h>

int main(void)
{
  double vx;
  double vy;

  printf("Enter the 1st number : "); scanf("%f" , &vx);
  printf("Enter the 2nd number : "); scanf("%f" , &vy);

  printf("\a\n\nx is %f of y" , vx / vy * 100);
  return 0;
}

2 个答案:

答案 0 :(得分:1)

虽然scanf是可变参数函数,但无法提升输入。scanf将指针作为输入,因此您需要将其指定为%lf。如果输入是变量而不是指针,则C会将float提升为double。在您的计划scanf中,函数有%f而不是%lf。下面的代码工作正常,MinGW上的输出为64.285714

另请参阅链接Correct format specifier for double in printf

int main(void)
{
  double vx;
  double vy;

  printf("Enter the 1st number : "); scanf("%lf" , &vx);
  printf("Enter the 2nd number : "); scanf("%lf" , &vy);

  printf("\a\n\nx is %f of y" , vx / vy * 100);
  return 0;
}

答案 1 :(得分:0)

你在scanf函数中犯了一个错误。

scanf函数中的

%f表示您的输入将被放入浮点变量。

使用%lf代替。

{{1}}
相关问题