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];
if( 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:
That sticks with integer arithmetic, but avoids the truncation to zero by making it something like
(600 / 9)instead of(6 / 9) * 100.