3つの重複しない乱数

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

3つの重複しない乱数

#1

投稿記事 by Iseuma14 » 9年前

C言語の乱数についてです
先日 、乱数を学び、試しに何か作ってみようと思い、
3つの重複しない10以下の整数を出すプログラムを作ってみたのですが、
数が重複してしまったり、3つ目の数が1に固定されていたりと挙動がおかしいです
修正すべき点を教えていただけると嬉しいです
ちなみに、環境はiPhoneでideoneのサイトで行っています
10回動かしてみた結果は、651、641、211、481、701、541、341、121、491、461
となりました

コード:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
  printf("コードブレイカー  3桁の数字を入力\n");
  	srand(time(0));
  		int ans[3] = {0};
  	ans[0] = rand() % 10;
  while(1)
{
  ans[1] = rand() % 10;
  	if (ans[1] != ans[0])
  		break;
 }
  
  while(1)
{
  ans[2] = rand() % 10;
  	if (ans[2] != ans[0] && ans[2]!= ans[1])
		break;
}
int i;     
for(i=1;i<=3;i++)
  {
    printf("%d\n",ans[i]);
   }
   return 0;
   }

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

Re: 3つの重複しない乱数

#2

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

  • インデントを整えましょう。
  • 出力するときのiの範囲がおかしく、確保した領域の外にアクセスしています。
    ans[0]、ans[1]、ans[2]に値を入れたことからも、それらを出力しないといけないことがわかるでしょう。

コード:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
    printf("コードブレイカー  3桁の数字を入力\n");
    srand(time(0));
    int ans[3] = {0};
    ans[0] = rand() % 10;
    while(1)
    {
        ans[1] = rand() % 10;
        if (ans[1] != ans[0])
            break;
    }

    while(1)
    {
        ans[2] = rand() % 10;
        if (ans[2] != ans[0] && ans[2]!= ans[1])
            break;
    }
    int i;
    for(i=0;i<3;i++)
    {
        printf("%d\n",ans[i]);
    }
    return 0;
}
オフトピック
ポインタを渡すべき所に整数の0を入れても、null pointer constantなので問題ありません。
N1256 6.3.2.3 Pointers さんが書きました: An integer constant expression with the value 0, or such an expression cast to type
void *, is called a null pointer constant. 55) If a null pointer constant is converted to a
pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal
to a pointer to any object or function.
複雑な問題?マシンの性能を上げてOpenMPで殴ればいい!(死亡フラグ)

Iseuma14
記事: 54
登録日時: 10年前

Re: 3つの重複しない乱数

#3

投稿記事 by Iseuma14 » 9年前

なるほど、forを1で初期化しているところに問題がありましたか
教えていただいたコードのforの部分の3を2にかきかえると確かに動作しました
ご指摘ありがとうございました

閉鎖

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