storing the contents in a array and displaying
I have written code to generate a prime number within a range. And then trying to store the generated prime number in an array:
if(prime)
printf("\n%d", n);
prime_array[k]=n;
k++;
Then trying to print the contents of array:
for(z=0;z<6;z++)
printf("%d\n",prime_array[z]);
The output that I get is incorrect. What is w开发者_StackOverflowrong?
Assuming everything else is correct, you should consider the following: printf
goes inside if
block, but everything else doesn't. It probably should be:
if(prime) {
printf("\n%d", n);
prime_array[k]=n;
k++;
}
in the code you've posted, you are trying to cast an integer (n) in something that seems to be a char (prime_array[k]), it can't work because 'n' and 'prime_array[k]' dont have the same type and also because you can't cast an integer in an array like that.
If you want to put an integer in an array, you can use the function sprintf from stdio.h. Man of this function : http://man.cx/sprintf%283%29
Anhuin.
精彩评论