我是C编程的新手,有些日子我会开始一些私人课程,当我怀疑时我正在训练,这实际上就是代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char yesorno[60]; //array, every cell contains a character
//But here initialize your array
printf("Do you want to start?\n");
scanf("%s", &yesorno);
if (strcmp(yesorno, "yes")==0)
{
int face, roll, frequency1 = 0, frequency2 = 0,
frequency3 = 0, frequency4 = 0,
frequency5 = 0, frequency6 = 0;
for ( roll = 1; roll <= 6000; roll++ )
{
face = 1 + rand() % 6;
switch ( face )
{
case 1:
frequency1++;
break;
case 2:
frequency2++;
break;
case 3:
frequency3++;
break;
case 4:
frequency4++;
break;
case 5:
frequency5++;
break;
case 6:
frequency6++;
break;
}
}
printf( "%s%13s\n", "Face", "Frequency" );
printf( " 1%13d\n", frequency1 );
printf( " 2%13d\n", frequency2 );
printf( " 3%13d\n", frequency3 );
printf( " 4%13d\n", frequency4 );
printf( " 5%13d\n", frequency5 );
printf( " 6%13d\n", frequency6 );
printf("Do you know which one has more chances?\n");
if (frequency1 > frequency2, frequency3, frequency4, frequency5, frequency6)
{
printf( " 1%13d has a better chance\n", frequency1 );
}
else if (frequency2 > frequency1, frequency3, frequency4, frequency5, frequency6)
{
printf( " 2%13d has a better chance\n", frequency2 );
}
else if (frequency3 > frequency1, frequency2, frequency4, frequency5, frequency6)
{
printf( " 3%13d has a better chance\n", frequency3 );
}
else if (frequency4 > frequency1, frequency3, frequency2, frequency5, frequency6)
{
printf( " 4%13d has a better chance\n", frequency4 );
}
else if (frequency5 > frequency1, frequency3, frequency4, frequency2, frequency6)
{
printf( " 5%13d has a better chance\n", frequency5 );
}
else if (frequency6 > frequency1, frequency3, frequency4, frequency5, frequency2)
{
printf( " 6%13d has a better chance\n", frequency6 );
}
}
else
{
printf("then go bay bay");
}
return 0;
}
这是我的问题&#34;:
我使用普通代码并在训练时添加了一些功能,如何比较2个字符串,这没关系,但现在我如何比较1变量大于其他5的变量以及为什么给它一个错误?
我认为我应该把它从第一个IF语句中删除,但这样做时它表示变量没有定义..所以我不得不以某种方式导入它们。
我正在使用code :: blocks
感谢大家!
答案 0 :(得分:1)
您在该代码中想要的是将每个频率与剩余的五个频率进行比较为 -
if (frequency1 > frequency2, frequency3, frequency4, frequency5, frequency6)
但是逗号运算符在c编程中具有最低优先级,因此该代码归结为
if ((frequency1 > frequency2), frequency3, frequency4, frequency5, frequency6)
所以,实际上发生的事情是将frequency1与frequency2进行比较,然后使用频率为6的最右边的变量值来检查始终返回true的if条件,从而首先如果语句将被执行
所以你可以这样做
if( (frequency1 > frequency2) && (frequency1 > frequency3) && (frequency1 > frequency4) && (frequency1 > frequency5) && (frequency1 > frequency6))
我们在这里做的是将每个频率值与frequency1值进行comap,然后对每个结果进行AND运算。