我的任务是:
我在弄清楚如何找到值最接近数组平均值的数组索引时遇到了麻烦。
在某些情况下,我会收到正确的值,但通常该值是第一个插入的,因此我认为这是巧合。
下面的代码可以正常工作,但不能完全正确。请有人可以帮助我正确编写代码-我的逻辑有什么问题吗?
enter code here
int main()
{
float vet[S];
int a = 0;
int i = 0.0;
float soma = 0.0;
float media = 0.0;
char correct;
float difference = 0.0;
float difference2 = 0.0;
float posicao = 1;
float closest = 0.0;
float answer = 100000;
printf(" -------------------\n");
printf("| Find the avarage |\n");
printf(" -------------------\n");
printf("Menu:\n");
printf("Press 1 para selecionar se quer inserir ou números:\n");
printf("Press 2 para receber valores aleatorios:\n");
printf("Press 3 for XXXX:\n");
printf("Press 4 for XXXX:\n\n");
printf("Select one option:\n");
scanf_s("%d", &a);
switch (a)
{
case 1:
for (i = 0; i < S; i++) {
printf("Insert a value:");
while (scanf_s("%f%c", &vet[i], &correct, 1) != 2 || correct != '\n') {
printf_s("incorrect type of data, please insert only numbers:\n");
while (getchar() != '\n');
}
soma += vet[i];
}
media = soma / 5.0;
for (i = 0; i < S; i++) {
printf("Array:%.2f ", vet[i]);
}
printf("\n\nAvarage:%.2f\n", media);
for (i = 0; i < vet[i]; i++) {
difference = abs(vet[i] - media);
difference2 = abs(answer - media);
if (difference < difference2) {
if (vet[i] < answer) {
answer = vet[i];
}
/*else if(difference == difference2) {
if (vet[i] < answer) {
answer = vet[i];
}
}*/
}
}
printf("\nThe closest number is:%.2f\n\n", answer);
return 0;
break;
case 2:
printf("valores aleatorios");
break;
case 3:
printf("tres");
break;
case 4:
printf("quatro");
break;
default:
printf("default");
break;
}
getchar();
getchar();
return 0;
}