【发布时间】:2014-12-01 18:56:46
【问题描述】:
首先我想和大家打个招呼!
我是一名自学成才的初级程序员,从 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、code::blocks 和在线编译器。同样有趣的结果。 为什么同一个变量(y),只声明一次,但在 2 个嵌套循环中使用,可以保存不同的值而不会造成任何问题?
我不认为这是推荐的做法,但是......它是如何工作的?
【问题讨论】: