小虫子在我的短小c code。为什么? [英] Small bug in my short C code. Why?

查看:99
本文介绍了小虫子在我的短小c code。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想不通为什么这个工程的投入90%,而不是其他。它的目的是要告诉你,你需要多少硬币取回变化。大多数测试大量做工精细,但如果你输入4.20(或$ 4.20),则返回23金币......应该是18金币(16个季度和2镍)。哪里错误?这里是我的code:

 的#include<&stdio.h中GT;
#包括LT&;&cs50.h GT;诠释主要(无效){    浮动变化= 0.00;    的printf(多少变化是欠?);
    变化= GetFloat();    浮季度=变更/ 0.25;
    变化 - =(int)的宿舍* 0.25;    浮角钱=变更/ 0.10;
    变化 - =(int)的硬币* 0.10;    浮镍=变更/ 0.05;
    变化 - =(int)的五分* 0.05;    浮动便士=(其他城市+ 0.005)/ 01。
    改变 - =(int)的硬币* 0.01;    INT总=(int)的宿舍+(INT)助攻+(INT)镍+(INT)便士;    的printf(%d个\\ N,总数);    返回0;
    }


解决方案

抛出了浮点计算。这是所有基于充其量百分之一,因此就使用整数除法/模数。 从不靠完美的精度浮点数。

 的#include<&stdio.h中GT;
#包括LT&;&cs50.h GT;诠释主要(无效){    浮fchange = 0.00;
    INT变化= 0;    的printf(多少变化是欠?);
    fchange = GetFloat();    改变=(INT)roundf(fchange * 100.0);    INT季度=变更/ 25;
    变化=改变25%;    诠释角钱=变更/ 10;
    变化=改变10%;    INT镍=更改/ 5;
    变化=改变5%;    的printf(%d个季度,%d个助攻,%d个镍,%d个便士\\ n,宿舍,硬币,镍,变更);    返回0;
}

I can't figure out why this works for 90% of the inputs, but not the others. It is meant to tell you how many coins you would get back in change. Most test amounts work fine, but if you enter 4.20 (or $4.20), it returns 23 coins... it should be 18 coins (16 quarters and 2 nickels). Where is the bug? Here is my code:

#include <stdio.h>
#include <cs50.h>

int main(void){

    float change = 0.00;

    printf("How much change is owed? ");
    change = GetFloat();

    float quarters = change/.25;
    change-= (int)quarters*.25;

    float dimes = change/.10;
    change-= (int)dimes*.10;

    float nickels = change/.05;
    change-= (int)nickels*.05;

    float pennies = (change+.005)/.01;
    change-=(int)pennies*.01;

    int total = (int)quarters+(int)dimes+(int)nickels+(int)pennies;

    printf("%d\n", total);

    return 0;
    }

解决方案

Throw out the floating-point calculations. this is all based on hundredths at best, so just use integer division/modulo. Never rely on perfect accuracy in floating point numbers.

#include <stdio.h>
#include <cs50.h>

int main(void){

    float fchange = 0.00;
    int change = 0;

    printf("How much change is owed? ");
    fchange = GetFloat();

    change = (int)roundf(fchange*100.0);

    int quarters = change/25;
    change = change % 25;

    int dimes = change/10;
    change = change % 10;

    int nickels = change/5;
    change = change % 5;

    printf("%d quarters, %d dimes, %d nickels, %d pennies\n", quarters, dimes, nickels, change);

    return 0;
}

这篇关于小虫子在我的短小c code。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆