temp()の回数が2の倍数回だと入れ替わらない

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
遊び人
記事: 42
登録日時: 6年前

temp()の回数が2の倍数回だと入れ替わらない

#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;
}
 

アバター
みけCAT
記事: 6734
登録日時: 13年前
住所: 千葉県
連絡を取る:

Re: temp()の回数が2の倍数回だと入れ替わらない

#2

投稿記事 by みけCAT » 6年前

temp関数で無駄に毎回乱数を初期化しており、かつ秒単位の時刻が変わらないうちに処理を終えているので、
毎回同じ場所を入れ替え、2の倍数回だと元に戻って入れ替わらないように見えるのでしょう。
何も考えず乱数(適当な数の列)を使いたいなら、srand関数はプログラム開始時に1回だけ呼び出しましょう。
temp関数しか書き換えてはいけない場合は、static変数を用いて最初に呼ばれた時のみsrandを呼び出すようにするといいでしょう。

↓参考
c - srand() — why call it only once? - Stack Overflow
オフトピック
rand()関数は性能が低い可能性があり、暗号などで用いる乱数には用いるべきではないというのはまた別の話。
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

遊び人
記事: 42
登録日時: 6年前

Re: temp()の回数が2の倍数回だと入れ替わらない

#3

投稿記事 by 遊び人 » 6年前

なるほど、srand関数は一度だけでいいのですね・・・
勘違いしておりました、ありがとうございます!

返信

“C言語何でも質問掲示板” へ戻る