我正在编写一个C程序来重复一系列指定时间的问题.我要求用户输入他们想要的尝试次数,然后我根据他们的数量运行以下循环,但问题是循环不断重复.它不会停止在指定的尝试次数.这是代码:
#include <stdio.h>
int main(void){
int num1,num2,high,low,average,subtotal,total_aver;
printf("Enter number of tries you want:");
scanf("%d", &num1);
while (num1 < num1 + 1) {
printf("Try number: ");
scanf("%d", &num2);
printf("Enter high ");
scanf("%d", &high);
printf("Enter low ");
scanf("%d", &low);
subtotal = high + low;
total_aver = subtotal / 2;
printf("Average temperature is: %d", total_aver);
}
}
Run Code Online (Sandbox Code Playgroud)
如果用户输入3尝试次数,那么程序应该在循环内部询问这些问题三次,但它会不断重复而不会结束.
while (num1 < num1 + 1) // condition is never false
Run Code Online (Sandbox Code Playgroud)
这是无限循环.它将继续并继续下去.
如果你想迭代次数,写这样的循环 -
int i=0;
while(i<num1){
// your code
i++;
}
Run Code Online (Sandbox Code Playgroud)
或者没有任何额外的变量 -
while(num1>0){
// your code
num1--;
}
Run Code Online (Sandbox Code Playgroud)