ttyp03 score 16657
2016/09/12 15:25 投稿
調べればやり方はいくつか出てくるのでしょうけど、考え方のひとつを紹介します。 |
まずword配列参照用の配列(idxとしておきます)を用意します。 |
word配列の要素数が20個なら同じく20個です。 |
初期値は、0~19です(idx[0]=0,idx[1]=1,...) |
乱数の範囲は0~19で、最大値を1問ごとに減らしていきます。 |
word配列の参照は、idx配列を介して行います。 |
int wordchange = rand () % randmax; |
word[idx[wordchange]] |
1問終わるごとに、idx配列の対象要素を削除し後ろを詰めます。 |
例えば、乱数の結果、2だったとすると、idx配列を次のように組み直します。 |
idx[0]=0 |
idx[1]=1 |
idx[2]=3 |
idx[3]=4 |
... |
それから`start = clock()`はfor文の外に出さないと1問ごとの時間になってしまいますよ。 |
それから`start = clock()`はfor文の外に出さないと1問ごとの時間になってしまいますよ。 |
修正版コード |
```c |
#include <stdio.h> |
#include <stdlib.h> |
#include <string.h> |
#include <time.h> |
int main() |
{ |
//単語設定 |
char *word[] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"}; |
char typing[256]; |
clock_t start,end; |
char idx[20]; |
int i; |
int randmax = 20; |
int wordchange; |
// idx配列の初期化 |
for(i = 0; i < 20; i++) idx[i] = i; |
srand((unsigned)time(NULL)); //乱数発生 |
int count; //ループ用変数 |
//時間計測スタート |
start = clock(); |
for(count = 0; count < 10; count++){ //ループ処理 |
wordchange = rand () % randmax; |
while(*word != typing){ //比較処理 |
puts(word[idx[wordchange]]); |
gets(typing); |
if(strcmp(word[idx[wordchange]],typing) == 0){ |
puts("\n\"right!\"\n"); //正解 |
break; |
} |
else{ |
puts("\n\"Nooooo!!!!\"\n"); //不正解 |
} |
} |
// idx配列を詰める |
for(i = wordchange; i < 20; i++) idx[i] = idx[i + 1]; |
randmax--; |
} |
end = clock(); //時間計測終了 |
printf("あなたは %d秒 でした。\n",end/CLOCKS_PER_SEC); //結果表示、CLOCKS_PER_SECで秒に変換 |
return 0; |
} |
``` |