#include<stdio.h> int main(void) { int digit[100]; int sum=0; float ave=0.0; int i=0,j=0; for(i=0;i<100;i++) { scanf("%d",&digit[i]); if(digit[i]==-1) break; } for(j=0;j<i;j++) { sum +=digit[i]; } ave = sum/i; printf("%d\n",sum); printf("%.2f\n",ave); return 0; }
digit[]数组里面的值莫名其妙的变成了-1,高手们可以加个printf语句试试digit[]的值。
本人在两个编译器里面都试过,为什么会这样啊。
谢各位高手解答!
解决方案
10
#include<stdio.h> int main(void) { int digit[100]; int sum=0; float ave=0.0f; int i=0,j=0; for (i=0;i<100;i++) printf("%d ",digit[i]); printf("\n"); for(i=0;i<100;i++) { printf("Input digit[%d]:",i);fflush(stdout); scanf("%d",&digit[i]); if(digit[i]==-1) break; } for(j=0;j<i;j++) { sum +=digit[j]; } ave = (float)sum/i; printf("sum:%d\n",sum); printf("ave:%.2f\n",ave); return 0; } //1311096 27 32 0 35 -1473595837 1311096 0 0 1 2090180133 268435456 1244912 2090180013 1315560 2090180041 1244976 13241797 -2136591274 3623968 3604840 56 3623968 3623976 3605848 -1995983848 56 0 3604480 1244244 0 1244828 2090172640 2090180464 -1 2090180460 270589708 3604480 0 48 0 0 2147348480 -1999473920 1244884 270609247 1244932 270608376 0 270609891 3624008 205 12 0 0 2147348480 0 2147348480 0 1244892 270579140 270944128 1244948 270609028 9 270609019 0 0 2147348480 36240080 1318752 1245104 270608376 270889264 -1 1244980 270608879 0 0 0 270887808 1320147 1245024 270579359 1320144 3624016 3624020 1245012 1245020 1320144 1320144 2 3624008 4 1245032 270577712 1245120 4199150 //Input digit[0]:9 //Input digit[1]:8 //Input digit[2]:7 //Input digit[3]:6 //Input digit[4]:-1 //sum:30 //ave:7.50 //
20
sum += digit[i];应该是sum += digit[j];
#include<stdio.h> int main(void) { int digit[100]; int sum = 0; float ave = 0.0; int i = 0, j = 0; for (i = 0; i < 100; i++) { scanf("%d", &digit[i]); if (digit[i] == -1) break; } for (j = 0; j < i; j++) { sum += digit[j]; } ave = sum / i; printf("%d\n", sum); printf("%.2f\n", ave); return 0; }