首页 > 解决方案 > 使用 scanf 时出错:使用浮点数忽略返回值

问题描述

这是我的代码,我不确定为什么每次尝试测试时都会出错。它一直说 scanf 忽略了返回值


#include <stdio.h>
#include <math.h>


int main(void) {

    float money, tax, result;

    printf("Enter the amount of money.");
    scanf("%f", &money);

    tax = 0.05 * money;

    result = tax + money;

    printf("With tax added: $%f", result);

    return 0;
}

标签: c

解决方案


这是因为返回值被忽略了。

您应该检查返回值scanf()以检查读数是否成功。

#include <stdio.h>
#include <math.h>


int main(void) {

    float money, tax, result;

    printf("Enter the amount of money.");
    if (scanf("%f", &money) != 1) {
        fputs("read error!\n", stderr);
        return 1;
    }

    tax = 0.05 * money;

    result = tax + money;

    printf("With tax added: $%f", result);

    return 0;
}

推荐阅读