我试图在两个循环中输出相同数量的 printf 语句,并且我必须使用 for 和 while 。不幸的是,我的第二个循环陷入了无限循环。我在第二个循环中做错了什么?
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
int main()
{
int x,c,v,b;
printf("Please enter a number between 1 and 25 \n");
scanf_s("%d",&x,&c);
for (x != 0; x--;)
{
printf("I'd rather be doing something else \n");
}
while (c!=0 ) {
printf("Programming is easy");
c--;
}
}
最佳答案
scanf_s("%d",&x,&c);
在此 scanf 中,您仅获得一个值。
这里变量c
正在获取一些垃圾值,因此它可能会运行很长时间,您认为这是无限循环。
使用
scanf_s("%d %d",&x,&c);
按照 for 循环语法。
for(variable initialization; condition; variable update)
在您的代码中,您已经拥有变量 x
的值。
条件检查x != 0
变量更新x--
所以应该是
for( ; x != 0; x--)
编辑:
如何让用户提示输入一系列数字,直到用户输入 -1 停止。
您可以使用的简单代码是。
scanf("%d,&a);
while(a != -1)
{
//do work here
//
//
//-----
scanf("%d,&a);
}
关于c - 我怎样才能在C中继续这个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809925/