我是C ++的新手。这是我的程序,总结两个3x3矩阵,我只是不知道如何退出while循环,似乎我只能退出for循环。 请帮忙。 这是我的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
int main() {
double a[3][3];
double b[3][3];
char str[40];
int step = 1;
double resultan;
while (1) {
for(int i=1; i<=3; i++) {
for(int j=1; j<=3; j++) {
if (step==1) {
printf("Enter value of matrix a row %d column %d = ", i, j);
scanf("%lf", &a[i][j]);
}
if (step==2) {
printf("Enter value of matrix b row %d column %d = ", i, j);
scanf("%lf", &b[i][j]);
}
if (step==3) {
resultan = a[i][j] + b[i][j];
printf("Matriks a[%d][%d] + Matriks b[%d][%d] = ", i,j,i,j);
printf("%lf + %lf = %lf\n", a[i][j],b[i][j],resultan);
}
if (i==3 && j==3) {
step++;
Sleep(1);
}
}
}
if (step==4) {
break;
}
}
}
答案 0 :(得分:6)
问题在于c数组的索引是从0
到N - 1
,所以只需更改
for (int i = 1 ; i <= 3 ; i++)
到
for (int i = 0 ; i < 3 ; ++i)
此外,永远不要忽略scanf()
的返回值,请阅读this documentation
最后使用while
循环是没有意义的,除非在非常罕见的情况下,条件是有原因的。人类读者在找出while
循环何时停止而不是
while (1)
使用
while (step < 4)
你的代码非常复杂,编写一个函数fill_array()
并传递给你想要填充的数组和它的大小。这样你就不需要这么复杂的逻辑了。
循环的主体做了太多的事情,如果你希望你的代码健壮且可维护,它应该只做一个。