C language: scanf function producing different res

2020-04-17 09:02发布

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

If I remove printf and scanf, and assign 1 as the value to the "amount" variable the result is correct.

I suspect scanf is causing the error. If so, why would that be?

Thank you for reading and feel free to ask for any additional info you require.

1条回答
Viruses.
2楼-- · 2020-04-17 09:30

The correct format specifier for double is %lf, not %f.

查看更多
登录 后发表回答