开发者

Always Returning Zero

Why this code always return 0

public int loveCal(String bname, String gname) {

    char[] boy_name = bname.toLowerCase().toCharArray();
    char[] girl_name = gname.toLowerCase().toCharArray();

    int boy = 0;
    int girl = 0;
    int love = 0;

    for(int i = 0; i < bname.length(); i++)
        boy += (int) boy_name[i];
    for(int i = 0; i < gname.length(); i++)
        girl += (int) girl_name[i];

    i开发者_StackOverflow社区f( boy > girl )
        love = (girl/boy)*100;
    else
        love = (boy/girl)*100;

    return love;
}


You're always performing integer arithmetic - and always dividing one non-negative integer by a greater one. That will always give zero. Multiplying that zero by 100 doesn't help.

The simplest way of fixing this is to just multiply by 100 first:

return boy > girl ? (girl * 100) / boy : (boy * 100) / girl;

That sticks with integer arithmetic, but avoids the truncation to zero by making it something like (600 / 9) instead of (6 / 9) * 100.


You probably need to do floating point calculations or maybe just change the order, to avoid rounding intermediate results down to 0 when everything is done with integers.

 return 100.0 * girl / boy;  // using floating points

 // or maybe just

 return 100 * girl / boy;    // using int, but multiplying first


It's because of this division:

  (girl/boy)

Using int, if this results in a fractionary number, returned int will be 0. Use floats or double instead.


Your divisions will always return 0 since the dividend is usually smaller than the divisor. It could in rare cases be equal!

Do the multiplication before the division:

if( boy > girl )
    love = (girl * 100) / boy;
else
    love = (boy * 100) / girl;


If:

boy > girl

then:

girl/boy

always returns 0 because of integer division rounding. Try this:

100.0f * girl / boy

Which is equivalent but casts girl to float first and avoiding integer rounding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜