这是我的代码:

#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);
}


该程序将有一个简单的输入,例如9.5,它表示£9.50,因此我使用double来存储我的值。另外,printf和scanf会将浮点数提高一倍,因此这并不重要。

但是,使用gcc进行编译时,出现错误消息:

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


该错误是什么意思,为什么会弹出?

最佳答案

使用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);
// ----------^


另外,您忽略了检查scanf的返回值。这不是可选的! scanf返回成功分配的项目数。如果返回N,但是您指定了要分配的M个变量,则最后一个(N-M)个变量将保持未分配状态(在您的情况下未初始化)。

尝试这样的事情:

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

关于c - 使用printf和scanf函数在C中进行 double ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38462756/

10-12 02:59
查看更多