gpt4 book ai didi

C语言 : scanf function producing different results with float and double types?

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:33 25 4
gpt4 key购买 nike

    **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;
}

如果我删除 printfscanf,并将 1 作为值分配给“amount”变量,结果是正确的。

我怀疑 scanf 导致了错误。如果是,为什么会这样?

感谢您阅读并随时询问您需要的任何其他信息。

最佳答案

double 的正确格式说明符是 %lf,而不是 %f

关于C语言 : scanf function producing different results with float and double types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133566/

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