Question

I need to use the 'long long' c type, to store data in a very large array. Since my code is large, I made up this fairly simple code which has the same problem. So, it iterates 222 times in the loop, and prints out when the loop reaches 50% (of storing values in the array) and 100% (when it's finished).

But it always gives me errors, for example in this case 50 % of the array should print the index 222/2 = 111 and 100% should print out index 222. However it always prints 100 and 200.

This is the simple code I'm using a below are the results.

#include<stdio.h>
#define S 222
int main(void){
    char *text = calloc(S, sizeof(char));   
     unsigned long long i;
    for(i=0; i<=S; i++){
    text[i] = 'a';

    if(i == (S/100)*50)) {printf("50percent\t and index : %llud index should be 111" ,i );}
    if(i == ((S/100)*100)){printf("100percent\t and index : %llud index should be 222", i);}        
}
return 0;
}

So I was wondering, if I was doing something wrong or if there is a logic explanation to that problem.

Thank you.

Était-ce utile?

La solution

In integer arithmetic, 222/100 == 2.

You could rework your comparisons to:

if (i == S/2) /* 50% */
if (i == S-1) /* 100% */

instead.

Autres conseils

thats because you're doing division first. If you divide 222 by 100 you get 2.22 which gets truncated to 2 as it's an int

SIZEG/100

will be formatted as a integer, which is 2, so your code will always print at index == 100 and index == 200

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top