所以在 C 語言中,我應該讓用戶從區間 [5, 25] 中輸入一個整數 n。然后,對于從 1 到 n 的每個數字,在一個新行中列印許多星星,所以它看起來像這樣:
"*
**
***"
我試過這樣做,但它不起作用。我在這里做錯了什么?
`
#include <stdio.h>
int main(void)
{
int n, i;
char star = '*';
do {
printf("Input an int from [5, 25]");
scanf("%d", &n);
} while (n < 5 || n >= 25);
for (i=0; i < n; i ){
star = '*';
printf("%c", star);
}
return 0;
}
`
uj5u.com熱心網友回復:
你不能寫star = '*';,因為你將star宣告為char,C是強型別的,char是char而不是char表。
您必須使用嵌套回圈,例如:
#include <stdio.h>
int main(void)
{
int n, i, j;
char star = '*';
do
{
printf("Input an int from [5, 25]");
scanf("%d", &n);
} while (n < 5 || n >= 25);
for (i = 1; i <= n; i )
{
for (j = 1; j <= i; j )
{
printf("*");
}
printf("\n");
}
return 0;
}
uj5u.com熱心網友回復:
你需要嵌套回圈
for (int i=0; i < n; i )
{
for(int j = 0; j <= i; j )
printf("*");
printf("\n");
}
或者如果你想使用字串:
char str[n 1];
for (int i=0; i < n; i )
{
str[i] = '*';
str[i 1] = 0;
puts(str);
}
https://godbolt.org/z/aT8brP1ch
uj5u.com熱心網友回復:
該宣告
star = '*';
不是在 C 中連接兩個字串的正確方法。為此,您可以為字串定義一個具有足夠空間的陣列并使用函式strcat,如下所示:
#include <stdio.h>
#include <string.h>
int main(void)
{
int n;
//initialize "stars" to an empty string
char stars[20] = {0};
do {
printf("Input an int from [5, 25]: ");
scanf("%d", &n);
} while (n < 5 || n >= 25);
//build the string containing the stars using repeated
//string concatentation
for ( int i = 0; i < n; i ) {
strcat( stars, "*" );
}
//print the string
printf( "%s\n", stars );
return 0;
}
該程式具有以下行為:
Input an int from [5, 25]: 5
*****
然而,這是非常低效且不必要的復雜。與其先在陣列中構建字串,然后再一次將其全部列印出來,通常更容易一次列印一個字符:
#include <stdio.h>
#include <string.h>
int main(void)
{
int n;
do {
printf("Input an int from [5, 25]: ");
scanf("%d", &n);
} while (n < 5 || n >= 25);
//print the stars one character at a time
for ( int i = 0; i < n; i ) {
putchar( '*' );
}
//end the line
putchar( '\n' );
return 0;
}
該程式具有與第一個程式相同的輸出。
您現在有了列印單行的解決方案。但是,您的任務涉及列印出幾行。這將需要一個嵌套回圈。根據關于家庭作業問題的社區指南,我現在不會提供完整的解決方案,因為您應該先嘗試自己做。
uj5u.com熱心網友回復:
char是一個整數型別——也就是說,它代表一個數字。'*'是一個Character Constant,它實際上具有 type int。
char star = '*';
star = '*';
在 ASCII 中,這與
char star = 42;
star = 42;
字串是一系列非零位元組,后跟一個零位元組(空終止字符,'\0')。您不能通過將兩個整數相加來構建字串。
要構建字串,您必須將每個位元組按順序放置在緩沖區中,并確保后面有一個空終止位元組。
#include <stdio.h>
#define MIN 5
#define MAX 25
int main(void)
{
int n;
do {
printf("Input an int from [%d, %d): ", MIN, MAX);
if (1 != scanf("%d", &n)) {
fprintf(stderr, "Failed to parse input.\n");
return 1;
}
} while (n < MIN || n >= MAX);
char buffer[MAX 1] = { 0 };
for (int i = 0; i < n; i ) {
buffer[i] = '*';
buffer[i 1] = '\0';
puts(buffer);
}
}
另外:永遠不要忽略scanf.
或者您可以避免使用字串,而直接列印字符。
for (int i = 0; i < n; i ) {
for (int j = 0; j <= i; j )
putchar('*');
putchar('\n');
}
uj5u.com熱心網友回復:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n,i,j;
printf("enter a number between 5 & 25");
scanf("%d",&n);
for(i=1;i<=n;i ){
for(j=1;j<=i;j ){
printf("*");
}
printf("\n");
}
return 0;
}
uj5u.com熱心網友回復:
字串連接不像 C 中那樣作業,而是使用 strcat()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/529169.html
標籤:C算法
