1
Well, this is the problem. I thought here and arrived at a code. However, both the sum and the k
(which would be the prime number positions) are incorrect. Any idea why?
#include <stdio.h>
#include <windows.h>
int main(void)
{
int k,i,j,d,v[101],soma,prim,f;
float med;
i=0;
while((i<101) && (j!=0) ){
i++;
printf ("Defina o valor do elemento %d => ", i);
scanf ("%d", &v[i]);
printf ("Para parar digite 0 => ");
scanf ("%d", &j);
}
k=0;
prim=1;
f=i;
soma=0;
while (f>2){ // verificação para ver se a posição do vetor(i) é um número primo
if (i%(f-1)==0){
prim = 0;
}
else{
k++;
soma=soma+v[f];
}
f=f-1;
}
med=soma/k;
printf("%d, %d, %d", k,soma,i); // só está servindo pra ver o que está dando errado no código
printf("A media e => %f \n", med);
system("pause");
}
what good is
prim = 0;
?– Math
The problem is in the way you are checking if a number is prime. From what I quickly understood of its algorithm, inside its while loop i is fixed (always with 101, for example). And you do 101% (100), then 101%(99), 101%(98) and so on, comparing if the result of this mod is 0. You’re not testing if a number of your vector is prime. One of the simplest (but inefficient) ways to check if a number is prime is to loop to the number in question by checking if it has 2 divisors, if it has prime.
– cantoni