C 中变量运算的错误结果
Wrong results with variables operations in C
我正在尝试编写这段代码:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
float input;
int quarters, cdimes, ldimes, nickels, pennies, left = 0, overleft, overleft2 = 0;
do
{
input = get_float("Enter a positive value between 0 and 1: ");
}
while (input <= 0);
int cents = round(input * 100);
if (cents >= 25)
{
quarters = cents/25;
**left = cents-(quarters*25);**
printf ("Number of quarters is %i and the money left is %i", quarters, left);
}
else if (cents >= 10)
{
cdimes = cents/10;
**overleft2 = cents-cdimes*10;**
printf ("Number of cdimes is %i and overleft2 is %i", cdimes, overleft2);
}
if (left >= 10)
{
ldimes = left/10;
overleft = left - ldimes*10;
printf ("Number of ldimes is %i. Over left is %i", ldimes, overleft);
}
但是在突出显示的部分,程序给出了错误的值。例如,当我输入数字 0.6 时,程序会乘以 100 并四舍五入(所以现在我有数字 60)。因为 60 大于 25,所以它转到第一个 if 子句。但是,当我想减去用户输入的四分之一数时,它没有给出正确的值。
我能做什么?
放弃left
,只用cents
。
// left = cents-(quarters*25);
cents %= 25;
删除 else
以检查季度 和 角钱。
// else if (cents >= 10)
if (cents >= 10)
可能还有其他问题。
我正在尝试编写这段代码:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
float input;
int quarters, cdimes, ldimes, nickels, pennies, left = 0, overleft, overleft2 = 0;
do
{
input = get_float("Enter a positive value between 0 and 1: ");
}
while (input <= 0);
int cents = round(input * 100);
if (cents >= 25)
{
quarters = cents/25;
**left = cents-(quarters*25);**
printf ("Number of quarters is %i and the money left is %i", quarters, left);
}
else if (cents >= 10)
{
cdimes = cents/10;
**overleft2 = cents-cdimes*10;**
printf ("Number of cdimes is %i and overleft2 is %i", cdimes, overleft2);
}
if (left >= 10)
{
ldimes = left/10;
overleft = left - ldimes*10;
printf ("Number of ldimes is %i. Over left is %i", ldimes, overleft);
}
但是在突出显示的部分,程序给出了错误的值。例如,当我输入数字 0.6 时,程序会乘以 100 并四舍五入(所以现在我有数字 60)。因为 60 大于 25,所以它转到第一个 if 子句。但是,当我想减去用户输入的四分之一数时,它没有给出正确的值。 我能做什么?
放弃left
,只用cents
。
// left = cents-(quarters*25);
cents %= 25;
删除 else
以检查季度 和 角钱。
// else if (cents >= 10)
if (cents >= 10)
可能还有其他问题。