当我键入'245'的int时,我如何实现这种格式:
(如果是奇数,则为矩形,偶数为三角形)
public
到目前为止,这是我的代码:
(我似乎无法同时输出三角形和矩形)
1
1 2
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
而且,当我在int中键入时我应该如何编码,编译器将提取第一个数字(从左到右)并相应地输出它?
任何帮助将不胜感激!
答案 0 :(得分:0)
以下是完整的代码。
Step1 :接受用户输入并检查它是奇数还是偶数。
Step2 :如果是奇数,则执行三角形其他矩形。
#include<iostream>
int main () {
int n;
cout<<"Enter number: ";
cin>>n;
if (n % 2 != 0)
{
for(int i = 1; i <= n; i++)
{
cout<<endl;
for(int j = 1; j <= n; j++)
{
cout<<j<<" ";
}
}
}
else
{
for(int i = 1; i <= n; i++)
{
cout<<endl;
for(int j = 1; j <= i; j++)
{
cout<<j<<" ";
}
}
}
return 0;
}
答案 1 :(得分:0)
你的印刷品都很相似。我建议:
#include<iostream>
using namespace std;
int main () {
int n;
cout << "Enter number: ";
cin >> n;
int i = 1;
int& rowLim = ((n % 2) ? n : i);
for(i = 1; i <= n; i++)
{
cout << endl;
for(int j = 1; j <= rowLim; j++)
{
cout<<j<<" ";
}
}
return 0;
}
答案 2 :(得分:0)
最简单的方法是使用string
,按char
重复char
并相应地输出。例如
#include <iostream>
using namespace std;
int main() {
string s;
cin >> s;
for (char c : s) {
int n = c - '0';
bool k = n % 2;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= (k ? n : i); ++j)
cout << " " << j;
cout << endl;
}
cout << endl;
}
return 0;
}
<强>输出强>
1
1 2
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
查看DEMO