简体   繁体   English

整数除法在 C 中返回 0

[英]Integer division returns 0 in C

An integer division caused by the elements of an array returns 0, I'm supposed to store the % in the same array....由数组元素引起的整数除法返回 0,我应该将 % 存储在同一个数组中....

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...这存储了一个 0 ......我认为它与数组是一个整数数组有关......所以我做了一个演员......

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仍然存储 0...我读到我必须将它们转换为浮点数但转换不起作用...我试过这个

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最后一个将存储每个百分比

如果你想要一个百分比,那么你正在寻找的是

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

This will always return 0.这将始终返回 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).如果您使用整数,然后除以总数,结果将 <1 并被截断为 0(因为结果必须是整数)。

You have to either use doubles (or floats) arrays, or scale the integers by a factor of eg 100 (not the total)您必须使用双精度(或浮点数)数组,或按比例缩放整数,例如 100(不是总数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM