我剛開始使用 C 編程,并且在實施一個程式時遇到了一些困難,該程式給出了一個帶有“高度”步數的樓梯。
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int height;
do
{
height = get_int("Height: ");
}
while(height > 8 || height == 0 || height < 0);
int width = 0;
int length = height;
while(width < height)
{
printf(" ");
printf("@");
for(width = 0; width < height; width )
{
printf("\n");
}
}
}
高度的第一行正在作業,但我在實際撰寫樓梯時遇到了困難。我想要這樣或類似的東西。
Height: 3
@
@
@
如果我將來遇到這樣的問題,我只是想學習如何實作這樣的東西。如果有人能進一步幫助我,我將不勝感激!
uj5u.com熱心網友回復:
這有效:
#include <stdio.h>
int main() {
// gets height input - replace with your get_int method
int height;
printf("Height: ");
scanf("%i",&height);
// loop over all the steps: 0 - height
for (int i = 0; i < height; i ) {
// add a space i number of times (where i is our current step number and so equal to width)
// notice that if we take top left as (0,0), we go 1 down and 1 right each time = current step
for (int j = 0; j < i; j ) {
printf(" ");
}
// finally, after the spaces add the character and newline
printf("@\n");
}
return 0;
}
uj5u.com熱心網友回復:
我在這里看到三個問題:
- 您正在列印換行符 (
\n) 而不是空格 ()。 - 為什么列印單個空格字符?
- 您正在列印
"@"之前(應該是什么)空格。 - 在空格和
@.
另外……樓梯的寬度總是等于它的高度;只是您正在列印的行正在推進……這有點令人困惑。
uj5u.com熱心網友回復:
#include <stdio.h>
int main(void)
{
int height = 5;
for(int i=0; i<height; printf("%*s\n", i, "@"));
}
輸出:
Success #stdin #stdout 0s 5572KB
@
@
@
@
@
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348689.html
下一篇:使用結構隱式宣告函式
