Two-dimensional arrangement practice
First, sorry for my poor开发者_JAVA百科 language. I'm using VC++ Express myself.
Now I'm studying about arrangements. The book gave me a project like so:
- Make a 5x5 matrix.
- Each column is for subjects (4 of them)
- Each row is for students (same, 4 of them)
- Each cell saves a score.
- At the end of each row/column, sum the row/column.
And this is my answer program:
int main(void)
{
int arr[5][5];
int i,j;
while(1)
{
printf("student: 1.Jim,2.Jombi,3.Joly,4.Moran if you done, type 0\n");
scanf("%d", &i);
if(i=0)
break;
printf("subject: 1.english,2.spanish,3.poolish,4.flash\n");
scanf("%d", &j);
printf("insult score!\n");
scanf("%d", arr[i-1][j-1]);//insulting score
}
for(i=0;i<4;i++)//initialization of sum parts
{
arr[i][4]=0;
arr[4][i]=0;
}
for(i=0;i<4;i++)
for(j=0;j<4;j++)
arr[4][i]+=arr[j][i];
for(i=0;i<4;i++)
for(j=0;j<4;j++)
arr[i][4]+=arr[i][j];
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
printf("%d ",arr[i][j]);//printing result
printf("\n");
}
return 0;
}
I completely don't know why this code doesn't work. Even when I tried only "while" part, it didn't work also. Why is this?
As has been pointed, you have an if
wrong
if (i == 0)
/* ^^^ */
And you have a scanf
wrong too
scanf("%d", &arr[i-1][j-1]);
/* ^^^ */
And you really, Really, REALLY shoud initialize the array with something (possibly zeroes)
int arr[5][5] = {0};
if(i=0)
I don't know if this is the source of your problem, but this should be:
if(i==0)
The index in your last for
loop is one-off. Should be 4
, you use 5
.
A couple of points:
- You're missing the
&
(address-of) operator in yourscanf()
call, so you'll pass the integer in the array instead. - Consider just doing a simple
memset(arr, 0, sizeof arr);
before the input loop to make sure the array is clear, rather than the nestedfor
s to zero out just the sums. Safer, shorter, easier to understand. - Add instrumentation, such as printing the matrix after the input step, to make sure it looks alright.
精彩评论