c++ - 如果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;
}
解决方案
可以使用setw和setfill简化整个程序,以便在需要的地方插入前导零字符。 #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;
}
推荐阅读
- mpeg-dash - 如何在流式传输视频时在 dash.js 播放器中获取比特率?
- angular - Protractor E2E 测试:LoginPage
- ios - 如何使用 Swift 获取推送通知状态?
- javascript - 为什么相同的 async/await 函数在某处工作而不在其他地方工作?
- c# - 使用 Razor Pages 在表格中显示数据时出现问题
- python - 如何在此查询中添加 if 条件?
- python - 得到 ImportError: cannot import name 'PandasError'
- javascript - 尝试离线导出到 Highcharts
- python-3.x - 如何从 AWS lambda 重建对 Amazon lex 的响应?
- python - 将列表传递给渲染(请求)时CSS失败