rand関数で1から100までの乱数を生成して、もし30なら30%の確率で任意の処理をさせるコードを教えてください。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main(void) {
srand((unsigned)time(NULL));
//trueになったら死ぬ、金が手に入る
bool m_flag = false, d_flag = false;
//死ぬ確率
int num_pro_d = rand() % 100 + 1;
//何万円もらえるか
int num_pro_m = 100 - num_pro_d;
printf("%d%%の確率で死ぬ\n",num_pro_d); printf("%d%%の確率で%d万円手に入る\n",num_pro_m, num_pro_m); double tmp_random = (double)rand()/RAND_MAX; if (tmp_random < (double)num_pro_d/100) { d_flag = true; } if (1 - tmp_random < (double)num_pro_d/100) { m_flag = true; } if(m_flag == true){ printf("%d万円手に入れた\n",num_pro_m); } if(d_flag == true){ printf("%d%%の確率で死んだ\n",num_pro_d); } return 0;
}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。