【发布时间】:2014-04-03 17:19:54
【问题描述】:
**Code A returns the correct conversion: 6.55957.**
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float convert(float currencyA)
{
float currencyB = 0;
currencyB = 6.55957 * currencyA;
return currencyB;
}
int main(int argc, const char *argv[])
{
float amount = 0;
printf("How much\n");
scanf("%f", &amount);
printf("You get %f in currencyB", convert(amount));
return 0;
}
**Code B returns an incorrect conversion: 0.051247.**
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double convert(double currencyA)
{
double currencyB = 0;
currencyB = 6.55957 * currencyA;
return currencyB;
}
int main(int argc, const char *argv[])
{
double amount = 0;
printf("How much\n");
scanf("%f", &amount);
printf("You get %f in currencyB", convert(amount));
return 0;
}
如果我删除 printf 和 scanf,并将 1 作为值分配给“数量”变量,则结果是正确的。
我怀疑是 scanf 导致了错误。如果是这样,为什么会这样?
感谢您阅读并随时询问您需要的任何其他信息。
【问题讨论】:
-
建议您确保启用编译器警告。许多编译器很容易警告
double amount = 0; scanf("%f", &amount);。
标签: c floating-point double scanf floating-accuracy