Integer division returns 0 in C

耗尽温柔 提交于 2019-12-14 00:11:56

问题


An integer division caused by the elements of an array returns 0, I'm supposed to store the % in the same array....

array[6][i]=array[5][i]/total;

This stores a 0... I thought it had something to do with the array being an integer array... so I did a cast...

array[6][i]=(int)(array[5][i]/total); 

Still stored 0... I read I had to convert them to floating points but the casting doesn't work... I tried this

array[6][i]=(int)((float)array[5][i]/(float)total); 

the array declaration

int arreglo[7][5]={{1,194,48,206,45},{2,180,20,320,16},{3,221,90,140,20},{4,432,50,821,14},{5,820,61,946,18},{0,0,0,0,0},{0,0,0,0,0}};

and the last one will store each percentaje


回答1:


If you want a percentage, then what you're looking for is something like

array[6][i] = (int) (100 * ((float)array[5][i] / (float)total));



回答2:


This will always return 0.

If you are working with ints, and you divide by the total, the result will be <1 and truncated to 0 (as the result must be an integer).

You have to either use doubles (or floats) arrays, or scale the integers by a factor of eg 100 (not the total)



来源:https://stackoverflow.com/questions/13278685/integer-division-returns-0-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!