首页 > 解决方案 > 如何让程序只运行用户输入的数字?

问题描述

我有一个代码,当我输入我想运行的 for 循环的编号时,程序会运行之前的所有 for 循环,直到该编号为止。

#include <iostream>
using namespace std;
int main()
{
    int length, i, j, k, l, space, rows;
    char ch, draw;
    cout << "Enter your choice of shape: " << endl;
    cout << "1. Square" << endl;
    cout << "2. Right triangle" << endl;
    cout << "3. Equilateral triangle" << endl;
    cout << "4. Upside down triangle" << endl;
    cout << "5. Exit the program" << endl;
    cout << "Enter Option Number: " << endl;
    cin  >> draw;
    if (draw = 1)
    {
        cout << "Enter length of square : ";
        cin >> length;
        cout << "Enter character to draw shape with: ";
        cin >> ch;
        for (int i = 0; i < length ; i++)
        {
            cout << endl;
            for (int j = 0; j < length ; j++)
            {
                cout << ch;
            }
        }
    }
    if (draw = 2)
    {
        cout << "Enter length of triangle: ";
        cin >> k;
        cout << "Enter character to draw shape with: ";
        cin >> ch;
        for (i = 1; i <= k; i++)
        {
            for (l = 0; l < (k - i); l++)
                cout << " ";
            for (j = 0; j < i; j++)
                cout << ch;
            cout << endl;
        }

我希望,如果我输入 2,只输出三角形的代码,但它先输出正方形,然后输出三角形

标签: c++if-statement

解决方案


更改if(draw = 1)if(draw == 1)。您在比较运算符上犯了一个错误==。看看:https ://en.cppreference.com/w/cpp/language/operator_comparison


推荐阅读