首页 > 解决方案 > 如果for循环以01-09开头,如何启动我的else?

问题描述

如果我的输入是 45,如果打印出这个,我该如何专门制作我的代码?

01.02.03.04.05.06.07.08.09.10

11.12.13.14.15.16.17.18.19.20

21.22.23.24.25.26.27.28.29.30

31.32.33.34.35.36.37.38.39.40

41.42.43.44.45

#include <iostream>
#include <string>
using namespace std;

int main() {
    string dot = "";
    int x;
    cin >> x;
    if (x<=10){
        for (int n=1; n<=x; n++){
            cout << dot << n ;
            dot =".";
        }
    }
    else if(x>10&&x<=100) {
        for (int i = 1; i <=x; ++i){
            for (int j = 1; j <=10; ++j){
            cout << dot << x;
            dot=".";
            }
        cout << endl;
        }
    }
    else{
        cout << "OUT OF RANGE";
    }
   return 0;
}

标签: c++

解决方案


可以使用setwsetfill简化整个程序,以便在需要的地方插入前导零字符。 #include <iomanip>访问这些流修改功能。

#include <iomanip>
#include <iostream>

using namespace std;

int main()
{
    int x;
    cin >> x;
    for (int i = 1; i <= x; i++)
    {
        cout << setw(2) << setfill('0') << i;
        char delimiter = ((i % 10) && (i != x)) ? '.' : '\n';
        cout << delimiter;
    }
    cout << endl;

}

推荐阅读