任務是在不使用陣列的情況下輸出每一行的平方和之和。我已經撰寫了一個代碼并且它完成了這項作業,只是我找不到一種方法可以根據第一個輸入動態調整矩陣大小,這將是矩陣的大小,這樣就不用在每個輸入之后按“輸入”元素,用戶可以用“空格”分隔每個元素,并用“輸入”分隔行,就像在實際矩陣中一樣。如果有辦法,請告訴我。這是需要在每個元素后按“輸入”的代碼。
/*Take matrix size as input. read each element and give out the sum of squaresum of rows of the matrix*/
#include <stdio.h>
int main(){
int m,n; //matrix size row,column
int rowsum = 0,sum = 0,a,col,row = 0;
printf("Enter the size of matrix\n");
scanf("%d %d",&m,&n); //take row and col
while (row!=m) //calculate sum of each element of column one by one row-wise
{
col = 0; //start from col 1 i.e col 0
rowsum = 0;
printf("Enter elements of %d row\n",row 1);
while (col!=n){ //calculate sum of each element of rows one by one col-wise
scanf("%d",&a); //read the element
rowsum = a; //add read element to sum of that row
col ; //move to next element
}
sum = rowsum*rowsum; //add the sq. of that rowsum before moving on to next
row ; //move to next row
}
printf("%d is sum of squaresum of rows",sum);
return 0;
}
先感謝您。
uj5u.com熱心網友回復:
您可以在掃描時去掉下一個字符,這樣您只能在數字后輸入一個空格。此外,您可以通過這種方式在數字之間放置任何字符。掃描時使用“%*c”跳過一個字符。這是代碼:
/*Take matrix size as input. read each element and give out the sum of squaresum of rows of the matrix*/
#include <stdio.h>
int main(){
...
while (row!=m) //calculate sum of each element of column one by one row-wise
{
col = 0; //start from col 1 i.e col 0
rowsum = 0;
printf("Enter elements of %d row\n",row 1);
while (col!=n){ //calculate sum of each element of rows one by one col-wise
scanf("%d%*c",&a); //read the element
rowsum = a; //add read element to sum of that row
col ; //move to next element
}
...
}
return 0;
}
當大小選擇為 (2, 3) 時,行的一些可能輸入:
Enter the size of matrix
2 3
Enter elements of 1 row
1;2;3
Enter elements of 2 row
4;5;6
輸出:
261 是行的平方和的總和
另一種可能的方式:
Enter the size of matrix
2 3
Enter elements of 1 row
1 2 3
Enter elements of 2 row
4 5 6
輸出與上面相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438491.html
