我编码的时间不长(只有两个月)。 我的问题与循环中计数器的迭代有关。下面是我的程序 与同时:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int cnt=0;
int match;
int position;
int tries=0;
char letter;
int main()
{FILE *Difficult= fopen("/GODlvl.txt", "r");
char singl[19];
if (Difficult==NULL){
return -1;}
for(int i = 0; i < rnd1; i++)
fgets(singl, 21, Difficult);
int DashN1= strlen(singl);
printf("%s", singl);
for (int i=0; i<DashN1-1; i++)
{
singl[i]='_';
singl[DashN1]='\0';
}
for (int i=0; i<DashN1; i++) /**it adds an extra character ..possibly a space..**/
{
printf(" ");
printf(" %c", singl[i]);
}
do{
scanf(" %c", &letter);
if(letter==singl[cnt])
{
match=1;
position=cnt;
printf("match found");
}
if (position==cnt)
{
singl[position]=letter;
printf(" %s", singl);
}
cnt++;
tries++;
}
while(tries!=8);
}
do 循环从 0 开始运行,并在每一步后迭代。问题在于 if 条件;他们不测试 char 数组(singl)中的任何任意元素。我如何编辑此代码(无论是 if 条件还是循环)以针对任意索引运行。
最佳答案
读取letter的用户输入后,您可以请求在singl
中使用随机索引,只需执行以下操作:
srand((unsigned)time(NULL));
cnt = rand() % DashN1;
这意味着您的 do 循环应该如下所示:
do{
scanf(" %c", &letter);
srand((unsigned)time(NULL));
cnt = rand() % DashN1;
if(letter==singl[cnt]){
//....
}
}while(/*...*/);
请确保您这样做:
#include<stdlib.h>
为了访问srand
和rand
关于c - 刽子手编程: unscrambling words (c programming),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53574012/