我的导师给了我一个作业,我必须编写一个只包含while循环和打印的代码:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
我试了100次,失败了100次。由于我的知识有限,我开始认为我的导师只是弄乱了我的大脑。如果有可能,请向我介绍一个代码,按照该顺序打印数字。 感谢...
答案 0 :(得分:1)
int i = 1;
int LIMIT = 5;
while (i <= LIMIT)
{
int j = 1;
while (j <= LIMIT -i) //Loop to print the desired space.
{
cout << " ";
j++;
}
int k = i;
while(k)
{
cout<<k; //Printing the digits
k--;
}
cout << endl; //Adding new line character at the end.
i++;
}
跟你的老师打个招呼:)
答案 1 :(得分:-1)
尝试下面的代码。我还在这里创建了一个示例工作代码http://goo.gl/gJqias
#include <iostream>
using namespace std;
int main()
{
int start_Index=1, maximum_Index=5;
while(start_Index<=maximum_Index)
{
//below loop prints leading whitespaces
//note that there are two whitespaces per number
int temp_var=start_Index;
while (maximum_Index-temp_var>0)
{
cout <<" ";
temp_var++;//note the post increment operator.
}
//below whiel loop prints lagging numbers with single whitespace before them
temp_var=start_Index;
while(temp_var>0)
{
cout<<" "<<temp_var--;//note the post decrement operator.
}
//Now we start over to next line
cout<<endl;
//Increment the start_index by 1
start_Index++;
}
return 0;
}
答案 2 :(得分:-1)
int main(void)
{
char str[11] = " ";// Filled with 10 blank spaces
int i=0;
while(i < 5)
{
str[9 - 2*i] = (i+1) + 48;// +48 will give equivalent ASCII code
printf("%s\n",str);
i++;
}
return 0;
}