2014-12-01 51 views
1

首先,我想向大家打招呼!2个嵌套循环中使用的相同变量可以有不同的值吗?

我是自学成才的,初学编程的,开始与C,并开始真正喜欢上这个。

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#define NUMBERS 6 
#define BALLS 6 

int main() 
{ 
int x, y, z, numbers[BALLS]; 

for (x = 0; x < BALLS; x++) 
    numbers[x] = -1; 

srand((unsigned)time(NULL)); 

puts("\t\tTHE AMAZING LOTTERY\n\n"); 
printf("Have you ever won at a lottery?\n"); 
printf("You can try your luck now! %c\n\n" , 2); 
printf("Quick, write down 6 numbers and then press \"Enter\""); 
getchar(); 

for (y = 0; y < BALLS; y++) 
{ 



/* This is the intriguing part*/ 

printf("%d\n", y); 



    label: 
    z = rand() % NUMBERS+1; 

    for (y = 0; y < BALLS; y++) 
    { 
     if (z == numbers[y]) 
      goto label; 
     else if (numbers[y] != -1) 
      continue; 
     else 
     { 
      numbers[y] = z; 
      break; 
     } 
    } 
} 
printf("\n\nToday's numbers are %c\a ", 16); 
for (x = 0; x < BALLS; x++) 
    printf("%d, ", numbers[x]); 

printf("\n\n\nWell...\n\t..tough luck buddy.."); 
printf("\n\n\n\tMaybe next time.. %c" , 15); 
putchar('\n'); 
getchar(); 

return 0; 
} 

在3级不同的编译器,c4droid,代码::块尝试,以及在线编译:

今天我偶然发现了一些非常有趣和迷人的在我的测试程序之一,同时绊倒。同样有趣的结果。 为什么相同的变量(Y),宣称只有一次,但在2个嵌套循环使用,而不会造成任何问题持有不同的价值观?

我不认为这是一个值得推荐的做法,但是......怎么来它的工作原理?

回答

1

你的代码是有点复杂。它不应该像你说的那样工作,除非你像“for(int y = 0; ...)”那样定义循环变量:编写一个简单的代码并测试它:

int i = 0; 
for (i = 0; i < 5; i++) { 
     printf("in first loop with i = %d\n",i); 
    for (i = 0; i < 2; i++) { 
     printf("in second loop with i = %d\n",i); 
    } 
} 
+0

好方法进入一个〜无限循环! 是啊,你的程序工作,因为它应该,但如果你试图编译我的,你会看到,不知怎的,大for循环记得离开的地方,并从那里继续,而不是小的地方for循环结束... 。尽管它使用完全相同的变量.... – Mugurel 2014-12-02 08:43:37

+0

你只有Ÿ在循环语句和其他地方的左侧,这样没人改变它。它的工作原理的唯一原因可能就像在进入内部循环之前y的值已经从内部循环中断开一样。放一些printf或调试它看看y是如何改变的... – SLeptons 2014-12-03 12:08:10

相关问题