我需要提示用户输入数字'n'然后在单独的行中打印打印星,例如,如果用户输入5,则应打印以下内容(使用while循环)
*
**
***
****
*****
****
***
**
*
我的代码没有输出
int n, x = 1, y = 1;
printf("enter a number : ");
scanf_s("%d", &n);
while (x <= n){
x++;
while (y <= x){
while (y >= n){
y--;
printf("*");
}
printf("\n");
}
system("pause");
}
}
答案 0 :(得分:0)
这应该适合你:
#include <stdio.h>
int main() {
int number, count, characterCount;
printf("Please enter a number:\n>");
scanf("%d", &number);
for(count = 1; count <= number; count++) {
for(characterCount = 1; characterCount <= count; characterCount++)
printf("*");
printf("\n");
}
for(count = 1; count < number; count++) {
for(characterCount = number-1; characterCount >= count; characterCount--)
printf("*");
printf("\n");
}
return 0;
}
评论后编辑:
while循环解决方案:
#include <stdio.h>
int main() {
int number, count = 1, characterCount;
printf("Please enter a number:\n>");
scanf("%d", &number);
while(count <= number) {
characterCount = 1;
while(characterCount <= count) {
printf("*");
characterCount++;
}
printf("\n");
count++;
}
count = 1;
while(count < number) {
characterCount = number-1;
while( characterCount >= count) {
printf("*");
characterCount--;
}
printf("\n");
count++;
}
return 0;
}
答案 1 :(得分:0)
你可以只使用2个for
循环:
int i,k,n,flag=0;
printf("Enter Number of Rows :");
scanf("%d",&n);
for(i=-n;i<=n;i++)
{
if(i < 0)
{
i = -i;
flag=1;
}
for(k=(n-i)+1;k>0;k--)
{
printf("*");
}
if(flag==1)
{
i=-i;flag=0;
}
printf("\n");
}
例如,如果用户输入值2
,则会打印
*
**
***
**
*