限制输入并再次询问用户正确的范围

时间:2018-11-25 14:08:09

标签: c++ visual-studio

我被这个程序卡住了:我必须限制输入,但是如果我输入一个大于或等于100的值,该程序将完全忽略if语句 显示错误,但继续要求用户输入并运行

这是我的代码:

#include<iostream>
using namespace std;

int main()
{
    int a[4][4], big1, n, m, i, j, loc1, loc2;
    cout << "Enter no of rows and columns:";
    cin >> m >> n;
    cout << "Enter the array:\n";

    if (n > 100 || m>100 )
    {
        cout << "Error! number should in range of (1 to 99)." << endl;
        cout << "Enter the number again: ";
        cin >> m >> n;
    }
    else 
        for (i = 0; i < m; i++)
        {
            for (j = 0; j < n; ++j)
            {
                cin >> a[i][j];
            }
        }

cout << endl << "Entered Matrix: " << endl;

for (i = 0; i < m; ++i)
    for (j = 0; j < n; ++j)
    {
        cout << " " << a[i][j];
        if (j == n - 1)
            cout << endl << endl;
    }


big1 = a[0][0];
loc1 = 0;
loc2 = 0;
for (i = 0; i < m; ++i)
{
    for (j = 0; j<n; ++j)
    {
        for (int i = 0; i<4; i++)
            for (int j = 0; j<4; j++)
                if (a[i][j]>big1)
                {
                    big1 = a[i][j];
                    loc1 = i;
                    loc2 = j;
                }
    }
}

cout << "\nLargest number:" << big1 << endl;
cout << "The position that had the largest number is in " << " Row " << loc1 << " " << "Column " << loc2 << endl;
system("pause");
return 0;
}

1 个答案:

答案 0 :(得分:0)

我添加了一段时间以重复检查,直到数字降至100以下。请注意,如果您超过4行* 4列,则“ int a [4] [4],..”行将超限。我建议在知道行和列时将其初始化移到较低的位置。

尝试一下:

#include<iostream>
using namespace std;
int main()
{
int big1, n, m, i, j, loc1, loc2;
cout << "Enter no of rows and columns:";
cin >> m >> n;
cout << "Enter the array:\n";

while (n > 100 || m>100 )
   {
      cout << "Error! number should in range of (1 to 99)." << endl;
      cout << "Enter the number again: ";
      cin >> m >> n;

   }
int a[m][n];
//else  redundant
for (i = 0; i < m; i++)
{
    for (j = 0; j < n; ++j)
    {
        cin >> a[i][j];
    }
}
cout << endl << "Entered Matrix: " << endl;
for (i = 0; i < m; ++i)
    for (j = 0; j < n; ++j)
    {
        cout << " " << a[i][j];
        if (j == n - 1)
            cout << endl << endl;
    }


big1 = a[0][0];
loc1 = 0;
loc2 = 0;
for (i = 0; i < m; ++i)
{
    for (j = 0; j<n; ++j)
    {
        for (int i = 0; i<4; i++)
            for (int j = 0; j<4; j++)
                if (a[i][j]>big1)
                {
                    big1 = a[i][j];
                    loc1 = i;
                    loc2 = j;
                }
    }
}

cout << "\nLargest number:" << big1 << endl;
cout << "The position that had the largest number is in " << " Row " << loc1 << " " << "Column " << loc2 << endl;
system("pause");
return 0;
}