C++ 编写一系列数字,例如:1 22 333 4444 55555
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19385193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a sequence of numbers like: 1 22 333 4444 55555
提问by Drago? Paul Marinescu
Okay so, I have to write a c++ program that reads a number and then proceeds to write every number up until the number that we read the same amount of times as its value. I have absolutely no idea how to explain this or what to search for so I'm hoping you understand what I need and can help me.
好的,我必须编写一个 C++ 程序来读取一个数字,然后继续写入每个数字,直到我们读取的数字与其值的次数相同。我完全不知道如何解释这个或搜索什么,所以我希望你明白我需要什么并且可以帮助我。
Basically, if we cin >> 5, the output should be 1 22 333 4444 55555
. I have a feeling this is extremely easy but nothing crosses my mind right now. I tried with 2 for statements but I can't seem to get it right.
基本上,如果我们 cin >> 5,输出应该是1 22 333 4444 55555
. 我有一种感觉,这非常容易,但我现在什么都没想。我尝试使用 2 for statements,但我似乎无法正确使用。
This is my attempt:
这是我的尝试:
int main ()
{
int i,j,n;
cout<<"n=";cin>>n;
for (i=n;i>=1;i--)
{
for (j=1;j<=i;j++)
{
cout << i;
}
cout<<" ";
}
}
回答by Igor Popov
#include<iostream>
int main()
{
int a;
std::cin>>a;
for(int i=1;i<=a;i++)
{
for(int j=0;j<i;j++)
std::cout<<i;
std::cout<<" ";
}
}
回答by Hanky Panky
#include <iostream>
int main()
{
int n;
cout << "Please enter a number";
cin >> n;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
cout<<i;
}
}
}
回答by ChuckCottrill
Yes, easy.
是的,容易。
- use cout to prompt for a number
- use cin to read a number
- you need an inner loop to print the copies of the digit, follow with a space
- you need an outer loop to loop from 1 to the number, follow with a newline (endline)
- 使用 cout 提示输入数字
- 使用cin读取一个数字
- 你需要一个内循环来打印数字的副本,后面跟一个空格
- 您需要一个外循环从 1 循环到数字,然后跟一个换行符(结束行)
Here is the answer,
这是答案,
#include <iostream>
using namespace std;
int main()
{
int upto, ndx, cdx;
cout<<"number=";
cin>>upto;
for(ndx=1;ndx<=upto;++ndx)
{
for(cdx=1;cdx<=ndx;++cdx)
cout<<ndx;
cout<<" ";
}
cout<<endl;
}
回答by sree
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,n=5;
clrscr();
for(i=0;i<n;i++)
{
for(j=1;j<=i;j++)
{
cout<<i;
}
cout<<endl;
}
getch();
}
回答by Saideep
#include<iostream>
using namespace std;
int main ()
{
int i,j; //declaring two variables I,j.
for (i=1; i<10; i++) //loop over the variable i so it variates from 1 to 10.
{
for (int j = 0; j<i; j++) //create an other loop for a variable j to loop over again and o/p value of i
{
cout <<i; //writes the value of i directly from i and also due to the loop over j.
}
cout<<endl; //manipulator to analyze the result easily.
}
return (0);
}