c - 程序在完成之前退出

标签 c modulo

问题低于上下文

上下文:为了使该程序能够提交并正常工作,我需要能够输入 8.68 作为扫描的金额。然后该程序需要能够计算每个扫描的数量需要提供硬币类型以及您提供 x 数量的硬币后的剩余余额

What the output should look like

问题:我的程序将运行到季度并全部正确,一旦到达一角硬币,其中有 0 角硬币,程序就会中断并退出。 (即使我一开始使用不同的数量,如果硬币的数量(在本例中一角硬币的值为 0),它也会在不同的点破裂) 我该怎么做才能确保它将运行并完成与上面显示的输出相同的内容。

代码:

#include <stdio.h>

int main()
{
    double amount;
    double GST = 1.13;
    double balance;
    int numLoonies;
    int numQuarters;
    int numDimes;
    int numNickels;
    int numPennies;
    int bal;

    printf("Please enter the amount to be paid: $"); //ask how much to be paid
    scanf("%lf", &amount);      //scans the input

    GST = amount * .13 + .005;

    printf("GST: 1.13\n");

    balance = (amount + GST);
    printf("Balance owing: $%.2lf\n", balance);

    numLoonies = balance;
    bal = ((balance - numLoonies)*100);

    printf("Loonies required: %d", numLoonies);
    printf(", balance owing $%1.2f\n", (float)bal/100);

    numQuarters = bal / 25;
    bal = bal % (numQuarters*25);

    printf("Quarters required: %d", numQuarters);
    printf(", balance owing $%1.2f\n", (float)bal / 100);

    numDimes = bal / 10;
    bal = bal % (numDimes * 10);

    printf("Dimes required: %d", numDimes);
    printf(", balance owing $%1.2f\n", (float)bal / 100);

    numNickels = bal / 5;
    bal = bal % (numNickels * 5);

    printf("Nickels required: %d", numNickels);
    printf(", balance owing $%1.2f\n", (float)bal / 100);

    numPennies = bal / 1;
    bal = bal % (numPennies * 1);

    printf("Pennies required: %d", numPennies);
    printf(", balance owing $%1.2f\n", (float)bal/100);

    return 0;
}

更新所以这是一个学校项目,应该提到这一点,但我必须使用模组来找到剩余的余额,并且我必须转换作为标准的一部分,双倍转换为 int。

是的,加拿大已经没有一分钱了,但我仍然必须这样做

最佳答案

(Even when I use a different amount in the beginning, it will break at a different point if the amount of coin, in this instance the dimes have a value of 0)

这是一个很大的线索。那么让我们看看一毛钱......

bal = bal % (numDimes * 10);

因此,假设 numDimes 为 0。那么 (numDimes * 10) 也为零。当您尝试计算 bal % 0 时,您认为会发生什么?如果您不确定,您可以将该表达式放入您的程序中并尝试一下。

另一个问题是,我认为您并不是真的想说bal % (numDimes * 10)。假设对于某些起始余额,numDimes 结果为 3...在这种情况下,您将得到 bal % (3 * 10)bal % 30 。这真的是你想要的吗?当您可能确实想要一个小于一毛钱值(value)的数字时,这会给出 0 到 29 之间的某个数字。如果我有 79 美分,并且我取出 7 个一毛钱,那么 79 % 70 确实给出了我应该剩下的 9,但这并不是实现这一目标的最直观方式。

关于c - 程序在完成之前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52433394/

相关文章:

c - 将指针放在数据结构后面有什么意义?

c - 尝试创建将用户输入字符串与C中的一组预定义输入字符串进行比较的程序

c - 哪个更好? 32 位 MCU 中的 int8_t 与 int32_t

algorithm - 如何有效解决涉及 'modulo' 操作的编码问题?

java - Java 的 % 运算符会溢出吗?

c - 如何计算给定系列的总和

c - 如何在c中通过匿名管道发送消息

C 中的 Cell 数据结构

Python While 循环,也使用取模和继续命令

python - 如何在没有循环的情况下求解公式 (y*known_number)%145 = 81 中的 y