马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 yg飞许 于 2024-1-22 20:58 编辑
为什,1~36对角和是222,改成720
求1~49对角线和,
下面只能求25对角线和,#include <stdio.h>
#include <math.h>
main(){
int num;
printf("请输入一个整数:");
scanf("%d",&num);
int row=sqrt(num);
int arr[row][row],times = 1,sum1 = 0,sum2 = 0;
for(int i = 0;i<=row-1;i++){
for(int j = 0;j<=row-1;j++){
arr[i][j] = times;
times = times + 1;
if(i==j){
sum1 = sum1 + arr[i][j];
}
//arr[i][j] = i * 5 + j+1;
}
}
printf("{") ;
for(int i = 0;i<=row-1;i++){
printf("{");
for(int j = 0;j<=row-1;j++){
if(i + j == row-1){
sum2 = sum2 + arr[i][j];
}
if(j==row-1){
printf("%d",arr[i][j]);
break;//continue
}
printf("%d,",arr[i][j]);
}
printf("},");
printf("\n");
}
printf("}\n");
printf("两条对角线之和为%d",sum1 + sum2);
}
#include <stdio.h>
#include <math.h>
int main(){
int num, sum1 = 0, sum2 = 0;
int row, i, j, count = 1;
printf("please input number you want to caculate:");
scanf("%d",&num);
row = sqrt(num);
int array[row][row];
for (i = 0; i < row; i++){
for (j = 0; j < row; j++){
array[i][j] = count++;
if (i == j){
sum1 += array[i][j];
}
if ((i + j) == row - 1){
sum2 += array[i][j];
}
}
}
printf("sum is %d.\n",sum1+sum2);
return 0;
}
|