首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套循环C++

嵌套循环C++
EN

Stack Overflow用户
提问于 2022-12-03 08:38:48
回答 3查看 38关注 0票数 0

我想问这个问题。这个输出是预期的输出。

代码语言:javascript
复制
*
*#
*#%
*#%*
*#%*#
*#%*#%

这是我的解决方案

代码语言:javascript
复制
#include <iostream>

using namespace std;


int main(){

  int a,b,n;

  cout << "Input the row";
  cin >> n;


  for (a = 1; a <= n; a++){
    for(b = 1; b <= a; b++){
        if (b == 1 || b == 1 + 3){
            cout << "*";
        }
        if (b ==2 || b == 2 + 3){
            cout << "#";
        }
        if (b ==3 || b == 3 + 3){
            cout << "%";
        }
    }
    cout << endl;
  }
}

这个解决方案只有在n= 6的情况下才能工作。如果我想要在每一行中做这个工作,当用户预先将该行输入n时,我该怎么办?谢谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-12-03 08:49:24

在这里,我尝试在您的if上使用模块"%“

代码语言:javascript
复制
#include <iostream>

using namespace std;


int main(){

  int a,b,n;

  cout << "Input the row";
  cin >> n;


  for (a = 1; a <= n; a++){
    for(b = 1; b <= a; b++){
        // After every first digits will cout #
        if (b % 3 == 2){
            cout << "#";
        }
        // The first after the third digit will cout *
        if (b % 3 == 1){
            cout << "*";
        }
        // The third digit after the second digit will cout % 
        if (b % 3 == 0){
            cout << "%";
        }
    }
    cout << endl;
  }
}
票数 0
EN

Stack Overflow用户

发布于 2022-12-03 08:45:37

要使您的解决方案适用于n的任何值,您可以使用模块化运算符%来检查给定的b值是每一行的第一个、第二个还是第三个元素。

以下是您可以修改代码的一种方法:

代码语言:javascript
复制
#include <iostream>

using namespace std;

int main() {
  int a, b, n;

  cout << "Input the row: ";
  cin >> n;

  for (a = 1; a <= n; a++) {
    for (b = 1; b <= a; b++) {
      // Use the modulo operator to check whether b is the first, second, or third element of each row
      if (b % 3 == 1) {
        cout << "*";
      } else {
        if (b % 3 == 2) {
          cout << "#";
        } else {
          cout << "%";
        }
      }
    }
    cout << endl;
  }

  return 0;
}

通过此更改,代码将输出任何n值的正确模式。

票数 0
EN

Stack Overflow用户

发布于 2022-12-03 09:20:45

只需添加一个很好的优化(注意: C++循环自然从0上升到不包括n,即for(int i = 0; i < n; ++i) --如果索引数组具有0的第一个索引和n - 1的最后一个索引,而n已经无效!)。

虽然您确实使用b % 3来决定哪个字符,而且您确实可以通过链接if(){} else if(){} else{}来使用这个字符(实际上,switch() { case: case: default: }可能会更好),但是您可以有一个更紧凑的版本,如下所示(而且更高效,因为它避免了条件分支):

代码语言:javascript
复制
for(int b = 0; b < a; ++b)
{
    std::cout << "*#%"[b % 3];
}

C-string文字"*#%"实际上表示长度为4的char数组(包括终止空字符),您可以像其他显式定义的数组(如int n[SOME_LIMIT]; n[7] = 1210;)一样对其进行索引.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74665170

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档