C语言 如何将数字打印成单独的行?



要解决的问题是,该代码应该在单独的行中获取数字,直到给出0。然后它应该输出y个数字,y次。例如,如果给定数字3,它应该在单独的行中打印3,3次。我尝试在单独的行中获取来自用户的输入。我的意思是一行有一个输入。然后在单独的行中打印数字。我不知道在哪里添加n来解决它。

这是我的代码:

#include <stdio.h>
int main() {
int y = 1;
while (y != 0) {
scanf("%d", &y);
if (y == (0)) {
break;
}
for (int i = 1; i <= y; i++) {
printf("%dn", y);
}
}
}

我试图在scanf%d旁边添加n,但它没有像我预期的那样工作。

这段代码的输出是这样的:
1
1
2
2
2
3
3
3
3
4
4
4
4
4
0

我期望的是,在输出之前,所有的输入都应该在单独的行中给出。像这样输入:

1
2
3
4
0

输出如下:

1
2
2
3
3
3
4
4
4
4

@ david。Rankin在下面解释说,如果你想保留输入,那就意味着你必须把它存储在某个地方。它通常在内存中,要么是原始输入字符串(char []),要么是您以适合输出的格式存储数据,如我下面使用的int input[LEN]
其他选项包括使用递归函数在堆栈中存储一个数字,或者使用文件或外部服务,如数据库(现在可能托管在云上)。

#include <stdio.h>
#define LEN 5
int main(void) {
// input
int input[LEN];
int i = 0;
for(; i < LEN; i++) {
if(scanf("%d",input + i) != 1) {
printf("scanf failedn");
return 1;
}
if(!input[i])
break;
}
// output (copy of input other than 0)
for(int j = 0; j < i; j++) {
printf("%dn", input[j]);
}
// output (repeated based on input)
for(int j = 0; j < i; j++) {
for(int k = 0; k < input[j]; k++) {
printf("%dn", input[j]);
}
}
}

和示例:

1 # input
2
3
4
0
1 # output (copy of input other than 0)
2
3
4
1 # output (repeated based on input)
2
2
3
3
3
4
4
4
4

这是你可以得到的最接近的递归函数,没有数组:

#include <stdio.h>
#include <stdlib.h>
void read_then_print() {
// input
int d;
if(scanf("%d", &d) != 1) {
printf("scanf failedn");
exit(1);
}
if(d) {
// output before recursion
printf("%dn", d);        
read_then_print();
}
// output after recursion
for(int i = 0; i < d; i++) {
printf("%dn", d);
}
}
int main(void) {
read_then_print();
}

和示例会话:

1 # input
1 # output before recursion
2 # input
2 # output before recursion
3 # ...
3
4
4
0
4 # output after recursion
4
4
4
3
3
3
2
2
1
#include<stdio.h>
int main()
{
int y;
do
{

scanf("%d",&y);

for(int i = 1;i <= y;i++)
{
printf("%dn", y);
}


}while(y != 0);


}

使用这个,这可能会解决你的问题。

您希望在处理行并打印结果之前收集所有输入。您可以使用数组来存储输入的数字,并在读取0后处理它们。

下面是修改后的版本:

#include <stdio.h>
#define MAX_LINES  256
int main() {
int input[MAX_LINES];
int y, n = 0;
while (n < MAX_LINES && scanf("%d", &y) == 1 && y != 0) {
input[n++] = y;
}
for (int i = 0; i < n; i++) {
y = input[i];
for (int i = 0; i < y; i++) {
printf("%dn", y);
}
}
return 0;
}

最新更新