c++ - 如何让程序只运行用户输入的数字?
问题描述
我有一个代码,当我输入我想运行的 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,只输出三角形的代码,但它先输出正方形,然后输出三角形
解决方案
更改if(draw = 1)
为if(draw == 1)
。您在比较运算符上犯了一个错误==
。看看:https ://en.cppreference.com/w/cpp/language/operator_comparison
推荐阅读
- java - 无法在 android studio 中解析符号 v7 和 appComapat Activity 导入
- php - 如何将包含空格的字符串作为参数传递给查询的 where 子句
- javascript - 你如何阅读和理解这个位移代码?
- javascript - 从vue js中的数组对象获取数组中的id
- python - 为什么 TikTok 网站会阻止 Selenium chromedriver?
- html - 如何根据容器的背景定位按钮?
- flutter - 无法获取 Flutter AppBar 主题变量
- django - 使用 axios 时,React 和 Nginx 会弄乱 url,API 调用不正确
- java - 为什么要在代码中插入大括号来调用TypeToken的getType方法?
- unity3d - 触发器 Collinder 不适用于 Input.GetKey