![](/img/trans.png)
[英]C program to write a GUESS game with certain constraints. Problems occuring - error in code, logic of code, suggesstions
[英]How to Fix the Logic Errors in My “Guess the Movie” Game as a C Program
我用 C 編程語言編寫了一個猜電影游戲。 我的邏輯似乎是正確的,但是每當我運行程序時,它都無法按預期工作。
這是我的代碼
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ran = 1;
int l, j = 0, i = 0, total = 0, d = 0;
char b;
char a[20];
char s[1000];
int z;
FILE *my;
printf("Enter your name:\n ");
scanf("%s", s);
ran = rand() % 6;
if (ran == 1)
{
my = fopen("my1.txt", "r");
}
else if (ran == 2)
{
my = fopen("my.txt", "r");
}
else if (ran == 3)
{
my = fopen("my2.txt", "r");
}
else if (ran == 4)
{
my = fopen("my3.txt", "r");
}
else if (ran == 5)
{
my = fopen("my4.txt", "r");
}
for (d = 0; d < 20; d++)
fscanf(my, "%c", &a[d]);
fclose(my);
printf("GUESS THE MOVIE GAME\n");
for (j = 0; j < 7; j++)
{
if (a[j] == 'm')
{
printf("M ");
}
else
{
printf("_ ");
}
}
printf("\n");
printf("Let's begin the game\n");
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
printf("enter character number %d\n",i+1);
scanf("%c", &b);
if (b == a[i])
{
printf("its a right guess\n");
total = total + 4;
i++;
}
else if (b != a[i])
{
printf("Wrong choice\n");
if (total == 1 || total == 0)
{
total=0;
}
else
{
total = total - 2;
}
}
}
}
printf("You have guessd the movie\n");
printf("The movie name is: ");
for (i = 0; i < 7; i++)
{
printf("%c",a[i]);
}
printf("Your score is %d\n",total);
}
這是我每次運行上述代碼時得到的程序 output:
輸入你的名字:
拉吉
猜猜電影游戲
_ _ _ _ M _ _
讓我們開始游戲吧
輸入字符編號 1
錯誤的選擇
輸入字符編號 1
我
錯誤的選擇
輸入字符編號 1
錯誤的選擇
輸入字符編號 1
除了評論中指出的不足之外,還有一個主要的邏輯錯誤:
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
…
}
}
如果循環遇到m
,它會無限重復。 消除if (a[i] != 'm')
或添加else ++i
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.