#1
by 遊び人 » 6年前
文字列同士を入れ替えるtemp()関数を何度か繰り返す場合、2の倍数回だと何度やっても入れ替わりません。
理由が分かる方がおられましたらお教えください。
コード:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
char string[4];
} Test[3];
Test test;
void temp()
{
int x, y;
char temp[4];
srand((unsigned)time(NULL));
x = rand() % 3;
while (1) {
y = rand() % 3;
if (x != y) break;
}
strcpy(temp, test[x].string);
strcpy(test[x].string, test[y].string);
strcpy(test[y].string, temp);
}
int main(void)
{
int i;
strcpy(test[0].string, "abc");
strcpy(test[1].string, "def");
strcpy(test[2].string, "ghi");
printf("before\n0:%s 1:%s 2:%s\n", test[0].string, test[1].string, test[2].string);
/*----------この部分----------*/
for (i = 0; i < 8; i++) {
temp();
}
/*----------------------------*/
printf("after\n0:%s 1:%s 2:%s\n", test[0].string, test[1].string, test[2].string);
return 0;
}
文字列同士を入れ替えるtemp()関数を何度か繰り返す場合、2の倍数回だと何度やっても入れ替わりません。
理由が分かる方がおられましたらお教えください。
[code=C]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
char string[4];
} Test[3];
Test test;
void temp()
{
int x, y;
char temp[4];
srand((unsigned)time(NULL));
x = rand() % 3;
while (1) {
y = rand() % 3;
if (x != y) break;
}
strcpy(temp, test[x].string);
strcpy(test[x].string, test[y].string);
strcpy(test[y].string, temp);
}
int main(void)
{
int i;
strcpy(test[0].string, "abc");
strcpy(test[1].string, "def");
strcpy(test[2].string, "ghi");
printf("before\n0:%s 1:%s 2:%s\n", test[0].string, test[1].string, test[2].string);
/*----------この部分----------*/
for (i = 0; i < 8; i++) {
temp();
}
/*----------------------------*/
printf("after\n0:%s 1:%s 2:%s\n", test[0].string, test[1].string, test[2].string);
return 0;
}
[/code]