嗨,我是一个begginer c程序员,我正在尝试制作一个过滤器,该过滤器应该根据其他变量更改变量,但它似乎不会因某种原因更改变量g1。我真的得到任何帮助,因为我现在被困在这里。感谢
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int car;
int g1;
int g2;
int sel1;
unsigned int iseed = (unsigned int)time(NULL);
srand (iseed);
g1 = 0;
car = rand() % 3 + 1;
printf("%d\n",car);
printf("select a door beetween 1 and 3\n ");
scanf ("%d",&sel1);
if (sel1 < 0)
{
printf("Invalid selection!\n");
return 0;
}
if (sel1 > 3)
{
printf("Invalid selection!\n");
return 0;
}
if (sel1 == 1)
{
if(car == 1)
{
g1 = 2;
g2 = 3;
}
if (car == 2);
{
g1 = 3;
g2 = 1;
}
if (car == 3);
{
g1 = 2;
g2 = 1;
}
}
if (sel1 == 2)
{
if(car == 1)
{
g1 = 3;
g2 = 2;
}
if (car == 2);
{
g1 = 1;
g2 = 3;
}
if (car == 3);
{
g1 = 1;
g2 = 2;
}
}
if (sel1 == 3)
{
if(car == 1)
{
g1 = 2;
g2 = 3;
}
if (car == 2);
{
g1 = 1;
g2 = 3;
}
if (car == 3);
{
g1 = 1;
g2 = 2;
}
}
printf("Behind door %d is a goat\n",g1);
return 0;
}
显然我没有足够的细节所以忽略这个我只是添加一些随机的细节。在小学数学中,变量是表示数字的字母字符,称为变量的值,它是任意的,未完全指定的或未知的。
答案 0 :(得分:1)
首先,正如@BLUEPIXY建议的那样,您应该删除;
。
我会将前两个sel1条件更改为仅设置一个,如下所示:
if (sel1 < 1 || sel1 > 3)
printf("Invalid selection!\n");
然后我会使用switch
个案和if
声明:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int car;
int g1;
int g2;
int sel1;
unsigned int iseed = (unsigned int)time(NULL);
srand(iseed);
g1 = 0;
car = rand() % 3 + 1;
printf("Car= %d\n", car);
printf("Select a door beetween 1 and 3:\n");
scanf("%d", &sel1);
if (sel1 < 1 || sel1 > 3)
printf("Invalid selection!\n");
switch (sel1)
{
case 1:
if (car == 1)
{
g1 = 2;
g2 = 3;
}
else if (car == 2)
{
g1 = 3;
g2 = 1;
}
else if (car == 3)
{
g1 = 2;
g2 = 1;
}
break;
case 2:
if (car == 1)
{
g1 = 3;
g2 = 2;
}
else if (car == 2)
{
g1 = 1;
g2 = 3;
}
else if (car == 3)
{
g1 = 1;
g2 = 2;
}
break;
case 3:
if (car == 1)
{
g1 = 2;
g2 = 3;
}
else if (car == 2)
{
g1 = 1;
g2 = 3;
}
else if (car == 3)
{
g1 = 1;
g2 = 2;
}
break;
}
printf("Behind door, %d is a goat\n", g1);
getchar();
getchar();
return 0;
}
示例:
答案 1 :(得分:0)
我注意到你没有说明sel1==0
会发生什么
你为sel1>3
和sel1==3
以及sel1==2
和sel1==1
以及sel1<0
加了引号,但你没有说明如果sel1==0
我认为g1是什么如果sel1为0,则不更改,否则更改
也许你应该在输入sel1时放一个空格,如下所示
scanf ("%d ",&sel1);
并在条件;
和if(car==2)
if(car==3)