矩阵行的平方和
任务是不使用数组输出每行的平方和。我已经编写了一段代码,它完成了这项工作,只是我找不到一种方法,可以根据第一个输入(即矩阵的大小)动态调整矩阵的大小,这样就不必在每次输入后按“输入”元素时,用户可以用“空格”分隔每个元素,并用“enter”分隔行,就像在实际矩阵中一样。如果有办法请告诉我。 下面是需要在每个元素后按“Enter”键的代码。
/*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;
}
先感谢您。
The task is to output the sum of the square sum of each row without using arrays. I have written a code and it doing the job, only I couldn't find a way that allows dynamic sizing of the matrix according to the first input which will be the size of the matrix, so that instead of pressing 'enter' after each element, the user can separate each element by a 'space' and separate the rows with 'enter', like in an actual matrix. If there is a way, please tell me.
Here is the code where one needs to press 'enter' after each element.
/*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;
}
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在扫描时删除下一个字符,这样您就只能在数字后输入一个空格。此外,您可以通过这种方式在数字之间放置任何字符。使用“%*c”在扫描时跳过一个字符。下面是代码:
当大小选择为 (2, 3) 时,行的一些可能的输入:
输出:
另一种可能的方式:
输出与上面的相同。
You can get rid of the next character while scanning so that you are able to enter only one space after a number. Also, you can put any character in between the numbers in this way. Use "%*c" to skip a character while scanning. Here is the code:
Some possible inputs for a row while size selected as (2, 3):
Output:
Another possible way:
Output is the same one above.