c - 使用 float 和整数

标签 c floating-point integer floating-point-conversion

我创建了一个类似 ATM 的程序,可以将钱存入一个人的帐户。当此人取款时,它会从帐户中扣除取款以及 0.50 的附加费。我遇到的问题是在这个程序中同时使用整数和 float 。我将整数帐户转换为 float ,但当我尝试打印该语句时收到错误消息。谁能告诉我我做错了什么?

#include <stdio.h>

int main (void) {
    int account = 2000;
    int withdrawal;
    float charge = 0.50;

    printf ("How much money would you like to take out? ");
    scanf ("%i", &withdrawal);

    while (withdrawal % 5 != 0) {
        printf ("Withdrawal must be divisible by 5. ");
        scanf("%i", &withdrawal);
    }

    account = ((float) account - charge) - withdrawal;

    printf("Remaining account: %.2f\n", account);

    return 0;
}

最佳答案

int account = 2000;
printf("Remaining account: %.2f\n", account);

这是错误的;对于整数,它应该是 "%d",或者更好,将您的 account 变量类型更改为可以代表您要收取的 0.50 的变量类型。我也不建议您使用(不精确的)float 来赚钱。当您的意思是 10.5 时,您不想撤回 10.499999997。您需要考虑要使用的精度和舍入规则。据我所知,这些都是法律或其他规定的。

关于c - 使用 float 和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8886400/

相关文章:

C++ 可执行文件无法在基于 Linux 的托管服务器上运行

c - 读取 "Scanf"语句中的 double 值

c - 如何修复此比较字符串(来自 argv 和 scanf)程序?

java - 在 Android 的 XML 中创建整数列表

python - 为什么 -2//4 的输出为 -1?

c - 从函数内部进行矩阵访问

python - 打印 Python 和 C++ double 时的精度差异

c - 浮点变量的大小和编译

php - 为什么 PHP 会将 (int) ((0.1+0.7)*10) 的结果转换为 7,而不是 8?

math - 将罗马数字翻译成阿拉伯数字