7-1 打印沙漏
实验代码:
#include<stdio.h>
int main()
{
int sum;
char c;
int n;
scanf("%d %c", &sum, &c);
for (int i = 0; i <= 100; i++)
{
if ((i*i) * 2 - 1 == sum)
{
n = i;
break;
}
else if ((i*i) * 2 - 1 > sum)
{
n = i - 1;
break;
}
}
int t = n;
int counter = 0;
while (t)
{
for (int i = 1; i <= counter; i++)
{
printf(" ");
}
for (int i = 1; i <= (2 * t - 1); i++)
{
printf("%c", c);
}
printf("\n");
counter++;
t--;
}
t = 2;
counter = n - 2;
while (t<=n)
{
for (int i = 1; i <= counter; i++)
{
printf(" ");
}
for (int i = 1; i <= (2 * t - 1); i++)
{
printf("%c", c);
}
printf("\n");
counter--;
t++;
}
if (sum == 0)
printf("0\n");
else
printf("%d\n", sum - (2 * n*n - 1));
system("pause");
return 0;
}
设计思路:
1.先给定义不同的值
2在给进行不同的循环for ,while。
3在用自定义函数
问题及解决方案
在for,和while的语句中容易出现数值出错,所以要避免,必须进行不断的重试和不要打错符号
运行结果