Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

Using printf and scanf functions for doubles in C

Here is my code:

#include <stdio.h>

int main (void)
{
double itemCost;
double paidMoney;
int changeDue;

printf("How much does the item cost: ");
scanf("%lf", itemCost);

printf("How much did the coustomer pay: ");
scanf("%lf", paidMoney);

changeDue = ( (itemCost - paidMoney) * 100);    

printf("Change due in pennies is: %i", changeDue);
}

The program will have a simple inputs like 9.5 which represents £9.50 therefore I am using double to store my values. Also printf and scanf promotes floats to doubles so it does not really matter.

However, when compiling with gcc, I get an error message saying:

cashReturn.c:10:15: warning: format specifies type 'double *' but the argument has type 'double' [-Wformat]

What does this error mean and why is it popping up?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You must pass a pointer to a variable of the specified type when using scanf.

double itemCost;
double paidMoney;
int changeDue;

printf("How much does the item cost: ");
scanf("%lf", &itemCost);
// ----------^

printf("How much did the coustomer pay: ");
scanf("%lf", &paidMoney);
// ----------^

Also, you're neglecting to check the return value of scanf. This is not optional! scanf returns the number of items successfully assigned. If it returns N, but you specified M variables to be assigned, then the last (N-M) variables are left unassigned (and in your case uninitialized).

Try something like this:

for (;;) {
    printf("How much did the coustomer pay: ");
    if (scanf("%lf", &paidMoney) == 1)
        break;   // success
    printf("Invalid input!
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...