期望:代码打印出x(你输入的)在矩阵中出现的次数...实际:代码打印出价值金额嘿伙计们,对于你们中的一些人来说,这个问题可能是愚蠢的,但我最近才开始学习C ++,所以请同情:((,我为我的英语不好道歉
#include <iostream>
using namespace std;
int NhapMang(int A[100][100], int &n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout << "Nhap A[" << i << "][" << j << "]: ";
cin >> A[i][j];
}
}
return 0;
}
int XuatMang(int A[100][100], int &n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout << A[i][j] << " ";
}
cout << "n";
}
return 0;
}
int SoLanXuatHien(int A[100][100], int &n, int &x)
{
int dem=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(A[i][j]==x);
{
dem++;
}
}
}
return dem;
}
int main()
{
int n, A[100][100],x;
cout << "moi nhap n: ";
cin >> n;
NhapMang(A,n);
XuatMang(A,n);
cout << "moi nhap x: ";
cin >> x;
cout << "nso lan xuat hien: n";
cout << SoLanXuatHien(A,n,x);
return 0;
}
矩阵:1 2 34 5 67 8 9x: 4
期望: 1实际: 9
问题是这一行
if(A[i][j]==x);
在C++中,即使是简单的分号也被视为语句。它实际上等效于这个:
if (A[i][j] == x)
;
在您的情况下,因为您没有在语句周围加上大括号,所以您的代码在某种程度上等效于以下内容:
....
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(A[i][j]==x) {
}
{
dem++; // dem will be incremented every time loop iterates. That's why you got 9
}
}
}
删除分号,一切都会正常工作。
更正的代码:
#include <iostream>
using namespace std;
int NhapMang(int A[100][100], int &n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout << "Nhap A[" << i << "][" << j << "]: ";
cin >> A[i][j];
}
}
return 0;
}
int XuatMang(int A[100][100], int &n)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cout << A[i][j] << " ";
}
cout << "n";
}
return 0;
}
int SoLanXuatHien(int A[100][100], int &n, int &x)
{
int dem=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(A[i][j]==x)
{
dem++;
}
}
}
return dem;
}
int main()
{
int n, A[100][100],x;
cout << "moi nhap n: ";
cin >> n;
NhapMang(A,n);
XuatMang(A,n);
cout << "moi nhap x: ";
cin >> x;
cout << "nso lan xuat hien: n";
cout << SoLanXuatHien(A,n,x);
return 0;
}