【发布时间】:2011-08-12 18:20:54
【问题描述】:
今天,当我尝试编写代码来仅对两个 2*2 矩阵进行加减运算时,我使用了 switch 语句,但出现错误:
在函数main()中绕过局部变量的初始化
代码
#include <iostream.h>
#include <conio.h>
#include <string.h>
int
main()
{
int mat1[2][2], mat2[2][2], mat3[2][2];
cout << "Enter the elements in the first matrix";
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> mat1[i][j];
}
}
cout << "\n\nEnter the elements of the second matrix";
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
cin >> mat2[k][l];
}
}
cout << "\n\nsaved......";
int choice;
cout << "\n\n\nFor adding these two matrices,press 1";
cout << "\nFor subtracting these two matrices,press 2";
cin >> choice;
switch (choice) {
case 1:
cout << "The addition of the two matrices will yield";
for (int a = 0; a <= 1; a++) {
for (int b = 0; b <= 1; b++) {
mat3[a][b] = mat1[a][b] + mat2[a][b];
}
}
break;
case 2:
cout << "The subtraction of the two matrices will yield";
for (int c = 0; c <= 1; c++) {
for (int d = 0; d <= 1; d++) {
mat3[c][d] = mat1[c][d] - mat2[c][d];
}
}
break;
}
getch();
return 0;
}
我还发现我可以通过将 case(s) 的代码放入大括号中来消除此错误,现在,
- 我的困惑是关于
error... - &
case....中大括号的要求
(我知道我没有使用新的编码约定,如<iostream>、std 命名空间等,因为我已经在Turbo C++ 编译器中编写了它,所以一个中肯的答案是谦虚地请求。)
【问题讨论】:
-
哪一行代码产生了这个错误?
-
这不是一个答案,但是 case 语句的两个分支都添加了两个矩阵,之后没有任何东西将它们打印出来。我猜这不是你的意思。
-
粗体字没有告诉我们它指的是哪一行;看我的回答。
标签: c++ switch-statement case