27.数列1,2,2,3,3,3,4,4,4,4,5,……

简介: 27.数列1,2,2,3,3,3,4,4,4,4,5,……

运用FOR循环

#include<iostream>
using namespace std;
 
int main()
{
    for(int i=1;i<=10;i++)
    {
        for(int j=1;j<=i;j++)
        {
            cout<<i<<" ";
        }
        cout<<endl;
    }
    return 0;
}


引申:数列1,2,2,3,3,3,4,4,4,4,5,……第100个是多少?

可以学习到如何从嵌套for循环中跳出

(1)在外层for循环中添加一个判断条件,用于循环跳出

#include<iostream>
using namespace std;
 
int main()
{
    int m=1;
    int a=100;
    for(int i=1;i<=100;i++)
    {
        for(int j=1;j<=i;j++)
        {
            cout<<i<<" ";
            m++;
            if(m>=100)
            {
                cout<<endl;
                cout<<"第100个数是: "<<i<<endl;
                break;
            }
        }
        if(a==m)//从嵌套for循环中跳出:在外层for中添加一个判断条件
        {
            break;
        }
        cout<<endl;
    }
    return 0;
}

(2)运用goto语句:不是很建议使用goto语句,因为会破坏程序的整体性

#include<iostream>
using namespace std;
 
int main()
{
    int m=1;
    int a=100;
    for(int i=1;i<=100;i++)
    {
        for(int j=1;j<=i;j++)
        {
            cout<<i<<" ";
            m++;
            if(m>=100)
            {
                cout<<endl;
                cout<<"第100个数是: "<<i<<endl;
                goto next;
            }
        }
        cout<<endl;
    }
    next:
        return 0;
}
目录
相关文章
|
人工智能
1311:【例2.5】求逆序对
1311:【例2.5】求逆序对
122 0
|
算法
斐波那切数列
斐波那切数列
100 0
7-8 菲波那契数列
7-8 菲波那契数列
59 0
LeetCode 665.非递减数列
LeetCode 665.非递减数列
95 0
LeetCode 665.非递减数列
|
开发者 Python
求斐波那契数列数列 | 学习笔记
快速学习 求斐波那契数列数列
求斐波那契数列数列 | 学习笔记