我在使用 C 语言时遇到的麻烦比我想象的要多。这段代码的目标是读取用户的输入,然后根据该整数输入“hello world”行的次数。我尝试了多种不同的方法,但每次我的代码只会执行 1 次。有什么建议吗?
#include <stdio.h>
int main()
{
double x;
printf("Enter a number from 1 to 5: ");
scanf("%f", &x);
for(int i =0; i <x; i++)
{
x= x-1;
printf ("Hello World.\n");
}
}
最佳答案
首先,您不必使用 double
,它是一种浮点类型。一个整数就足够了。
scanf("%d", &x);
在 for
循环中递减 x
是无用的:Hello world
将从 (x - 1) - 0 + 1 打印= x
次没有此指令。
for (int i = 0; i < x; i++)
{
printf("Hello world.\n");
}
关于c - For循环-多次C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18747120/