[英]Infinite While Loop In C
這段代碼創建了一個無限循環,我想按照一些步驟將數字首次顯示為0並打印該程序需要花費多少步驟
int debut,i;
printf("de (>= 1) ? ");
do
{
scanf("%d",&debut);
}
while (debut < 1);
int fin;
printf("a >= << << ) ? ");
do
{
scanf("%d",&fin) ;
}
while (fin < debut);
for (;debut<=fin;debut++){
i=0;
while(debut!=0)
{
if(debut%3==0)
{
debut+=4;
}
else if (debut%3!=0 && debut%4==0){
debut/=2;
}
else if (debut%3!=0 && debut%4!=0)
{
debut-=1;
}
i+=1;
}
printf("%d\n->%d",debut,i);
}
for(debut<=fin;debut++) {
while(debut!=0) {
//do stuff
}
//debut == 0, debut <= fin
}
好的,大量編輯我的答案。 我看錯了循環。
為了進入for
循環, debut
必須是<=fin
。 每當fin
>0
且進入for
循環時,您就會陷入for
循環中。
您陷入了while
循環中,直到除非debut == 0
返回true
為止。 只要debut++ <= fin
,您就會陷入for
循環中。 您正在while
循環中修改debut
,但是fin
保持不變。 因此, while
循環將debut
減少為0
,並且for
循環每次都會進入下一個迭代。
簡短的回答 :我懷疑您打算將while循環用於debut
的副本 ,而不是debut
。
debut == 3
和fin == 5
。 debut == 0
, fin == 5
和i == 12
。 debut
已減少為0
,因此,每次運行此代碼時,在for循環迭代結束時,我們將擁有一個debut == 0
,這將導致for循環永不退出。 在代碼中內聯顯示可能會更有用...
for (;debut<=fin;debut++){
// Let's assume we get here. We can assume some sane debut and fin values,
// such as the 3 and 5 suggested above.
int i=0;
while (debut != 0) {
// Stuff happens that makes debut go to zero.
}
// To get to this point, we __know__ that debut == 0.
// We know this because that's the condition in the while loop.
// Therefore, when we do the comparison in the for loop above for the
// next iteration, it will succeed over and over again, because debut
// has been changed to zero.
printf("%d->%d\n",debut,i);
}
就我個人而言,我懷疑您正在尋找一組數字的迭代次數。 對我來說,這聽起來像是使用功能的理想之地。 我建議的代碼看起來像這樣。
#include <stdio.h>
int iterations(int debut) {
int i = 0;
while(debut!=0)
{
if(debut%3==0)
{
debut+=4;
}
else if (debut%3!=0 && debut%4==0){
debut/=2;
}
else if (debut%3!=0 && debut%4!=0)
{
debut-=1;
}
i+=1;
}
return i;
}
int main() {
int debut = 3;
int fin = 5;
for (;debut<=fin;debut++) {
printf("%d -> %d\n", debut, iterations(debut));
}
}
另外,僅出於注意的目的,請注意,在最后給出的示例代碼中,我刪除了所有輸入的scanf代碼。 它與您的實際問題無關,它減少了任何人都需要掃描才能了解問題所在的代碼總數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.