" new_dollars =美元+美分/ 100"没变

时间:2016-06-01 02:26:43

标签: c

在输出中,new_dollars始终显示美元数,因此我不知道如何解决问题。请帮我弄清问题是什么。

int main(void)
{
    int dollars, cents, count, new_dollars;

    for ( count = 1; count <= 10; ++count){
        printf ("Enter dollars: ");
        scanf ("%i", &dollars);

        printf ("Enter cents: ");
        scanf ("%i", &cents);

        if ( cents >= 100 ){
            cents = cents % 100;
            new_dollars = dollars + cents / 100;
            printf ("%i\n", new_dollars);
            printf ("$%i.%2i\n\n", new_dollars, cents);
        }
        else {        
            printf ("$%i.%2i\n\n", dollars, cents);
        }
    }

    return 0;
}

2 个答案:

答案 0 :(得分:4)

评论者对整数除法是正确的。试试这个,它有两行进行交换计算的顺序,所以cents在需要它时仍然会有一个有用的值:

int main(void)
{
    int dollars, cents, count, new_dollars;

    for ( count = 1; count <= 10; ++count){
        printf ("Enter dollars: ");
        scanf ("%i", &dollars);

        printf ("Enter cents: ");
        scanf ("%i", &cents);

        if ( cents >= 100 ){
            new_dollars = dollars + cents / 100;
            cents = cents % 100;
            printf ("%i\n", new_dollars);
            printf ("$%i.%2i\n\n", new_dollars, cents);
        }
        else {        
            printf ("$%i.%2i\n\n", dollars, cents);
        }
    }

    return 0;
}

答案 1 :(得分:0)

  1. 将“int new_dollars”转换为“float new_dollars”;

  2. new_dollars =(浮动)美元+(浮动)美分/ 100;

  3. printf(“$%。2f \ n”,new_dollars);