C 编程 - While 循环和 scanf

标签 c

谁能告诉我为什么我的 scanf 函数只工作一次并且以连续循环结束。

#include <stdio.h>
#include <conio.h>

int main(void)
{
    int accno;
    float bbal, charge, rebate, limit, balance;

    printf("Enter account number (-1 to end):");
    scanf("%d", &accno);

    while (accno != -1) // User input phase
    {
        printf("Enter beginning balance:"); // User input phase
        scanf(" %.2f ", &bbal); // leave space after scanf(" 

        printf("Enter total charges:");
        scanf(" %.2f ", &charge);

        printf("Enter total rebates:");
        scanf(" %.2f ", &rebate);

        printf("Enter credit limit:");
        scanf(" %.2f ", &limit);

        balance = bbal - charge + rebate;

        // credit limit exceeded phase
        if (balance > limit)
        {
            printf("Account: %u", accno);
            printf("Credit limit: %.2f", limit);

            balance = bbal - charge + rebate;

            printf("Balance: %.2f", balance);
            printf("Credit limit exceeded!");
        }
        printf("Enter account number (-1 to end):");
        scanf("%d", &accno);
    }

    getch();
}

最佳答案

当我尝试编译问题中的代码时,收到一条警告,指出 scanf 格式字符串 %.2f 非法。如果我将其更改为 %f (也需要删除前导空格和尾随空格),那么一切都会按预期开始工作。我在 Mac 上使用 clang,但它应该与 Windows 相同。

/Users/jeremyp/dev/foo/foo.m:19:18: warning: invalid conversion specifier '.' [-Wformat-invalid-specifier]
scanf(" %.2f ", &charge);
       ~~^

无论如何,正如其中一条评论所述,货币不是 float 。存储货币的方法有很多,可能最好的是大整数类型,例如64 位 int 即可,但以美分或便士或您选择的货币中的任何最低面额单位存储货币。

关于C 编程 - While 循环和 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32525757/

相关文章:

c - 我如何编写 C 代码来使用 fork() 创建树?

c - 错误 : format %d expects type int, 但参数 2 的类型为 double(*)(int, int)

c - 从 VMS 迁移到 Unix

c - 为什么这个 for 循环会影响外部循环的变量?

c - 使用可变长度数组安全吗?

c - 这个 "a.out"文件是什么,是什么让它消失了?

c - 如何使用 BFS 查找 C 图中两个顶点之间的所有最短路径?

c - 如何删除C中的文本?

c - 按位表达式清除常量的低字节

c - 字符串数组插入问题