一道C语言题!请帮忙解决一下!!急,要考试了!!谢谢

题目是这样的:编写一程序P7-748.C实现以下功能
从键盘上输入矩阵的阶数n(n<=14), 矩阵中元素的值等于其位置的行数和列数之和的n倍(行列的值从0开始计数),如n=3时,矩阵为
0 3 6
3 6 9
6 9 12
先输出该矩阵(显示时每个数宽度为4、右对齐),然后计算输出sum1和sum2的值:sum1为矩阵中所有不靠边元素之和、sum2为矩阵的一条对角线元素之和。
我的解答时这样的:
#include <stdio.h>

int main(void)
{
int s1[14][14], i, j, n, sum1 = 0, sum2 = 0, sum3 = 0, sum;

printf("Enter n:");
scanf("%d", &n);

for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
s1[i][j] = (i + j) * n ;
}
}

for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%4d", s[i][j]);
}
printf("\n");
}

for (i = 0; i < n; i++)
{
sum1 += s1[i][i];
for (j = 0; j < n; j++)
{
sum2 += s1[i][j];
if (i == 0 || j == 0 || i == n - 1 || j == n - 1)
{
sum3 += s1[i][j];
}
}
}
sum = sum2 - sum3;

printf("sum1=%d\n", sum1);
printf("sum=%d", sum);

return 0;
}
然后就弄死不对!!会的给个答案吧!谢谢!!

printf("%4d", s[i][j]);应改为printf("%4d", s1[i][j]);

for (i = 0; i < n; i++)
{
sum1 += s1[i][i];
for (j = 0; j < n; j++)
{
sum2 += s1[i][j];
if (i == 0 || j == 0 || i == n - 1 || j == n - 1)
{
sum3 += s1[i][j];
}
}
}
sum = sum2 - sum3;

printf("sum1=%d\n", sum1);
printf("sum=%d", sum);

return 0;
}
改为:
for (i = 0; i < n; i++){
sum2 += s1[i][i];//sum1 += s1[i][i];
for (j = 0; j < n; j++){
sum += s1[i][j];//sum2 += s1[i][j];
if (i == 0 || j == 0 || i == n - 1 || j == n - 1){
sum3 += s1[i][j];
}
}
}
sum1 = sum - sum3;
printf("sum1=%d\n", sum1);
printf("sum2=%d\n", sum2);

且定义sum时要初始化为0
温馨提示:内容为网友见解,仅供参考
第1个回答  2010-07-05
哪里出错了?我感觉完全正确啊

Warning: Invalid argument supplied for foreach() in /www/wwwroot/www.t2y.org3v3b34/skin/templets/default/contents.html on line 47
相似回答