C++矩形的高度和宽度在3到20之间,程序检查非法条目

C++ height & width of rectangle between 3 to 20 with program checks for illegal entries

本文关键字:之间 程序 检查 非法 高度 C++      更新时间:2023-10-16

我正在尝试编写一个程序,允许用户使用任何给定字符选择矩形的高度和宽度(3 到 20 之间)。我需要输入非法条目,如果超出范围,则允许保持尝试输入。 下面的程序有效,但仅在小于 3 或大于 20 的情况下。我怎样才能让这个程序同时使用这两个条件?

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int height, width;
    char ch;
    do {
        cout<<"Enter desired height (3 to 20): ";
        cin>>height;
        if (height>3)
            cout<<"";
        else if (height<3)
            cout<<"Illegal entry."<<endl;
    } while (height<3);
    do {
        cout<<"Enter desired width (3 to 20): ";
        cin>>width;
        if (width>3)
            cout<<"";
        else if (width<3)
            cout<<"Illegal entry. "<<endl;
    } while (width<3);
    cout<<"What character would you like for your rectangle? ";
    cin>>ch;

    for (int i=0; i<height; i++) {
        for (int j=0; j<width; j++) {
            cout<<ch;
        }
        cout<<endl;
        cout<<endl;
    }
    return 0;
}

如何使用这两个条件使该程序工作?

你想使用逻辑和&&和逻辑或||

if ( (height>3) && (height < 20) )
    cout << "";
else if (height<3 || height > 20)
    cout << "Illegal entry." << endl;