Determine true and false using For loop statement

In C language, we can use the For loop statement to let the program make judgments based on known information. Take the following two examples.

Example 1:

Five athletes participated in the 10-meter platform diving competition. Someone asked them to predict the result of the competition
Player A said: B is second and I am third;
Player B said: I am second, E is fourth;
Player C said: I am first, D is second;
Player D said: C is last , I am third;
Player E said: I am fourth and A is first;
After the game, each player said half of the words correct, please program Determine the ranking of the competition.

The specific code is as follows:

#include<stdio.h>

int main()
{
	int a = 0;
	int b = 0;
	int c = 0;
	int d = 0;
	int e = 0;
		for (a = 1; a <= 5; a++)//使用五个for循环并嵌套起来,将每一个选手的名次都罗列出来。
		{
			for (b = 1; b <= 5; b++)
			{
				for (c = 1; c <= 5; c++)
				{
					for (d = 1; d <= 5; d++)
					{
						for (e = 1; e <= 5; e++)
						{
							if (((b==2) + (a==3) == 1) &&//根据五个运动员的描述写出if判断语句:
								((b==2) + (e==4) == 1) &&//B选手说:我第二,E第四;
								((c==1) + (d==2) == 1) &&//C选手说:我第一,D第二;
								((c==5) + (d==3) == 1) &&//D选手说:C最后,我第三;
								((e==4) + (a==1) == 1))//E选手说:我第四,A第一;
							{
								if(a*b*c*d*e == 120)//由于每位运动员都说对了一半,加入所有可能的条件
									printf("a=%d b=%d c=%d d=%d e=%d\n", a, b, c, d, e);
							}
						}
					}
				}
			}
		}
		return 0;
	} 

Example 2:

A murder occurred somewhere in Japan. Through investigation, the police determined that the murderer must be one of the four suspects
. The following are the confessions of the four suspects.
A said: It’s not me.
B said: It’s C.
C said: It’s D.
D said: C is talking nonsense
It is known that 3 people told the truth and 1 person told a lie.
Now please write a program to determine who is the murderer based on this information.

The specific code is as follows:

#include<stdio.h>

int main()
{
	char killer = 0;
	for (killer = 'a'; killer <= 'd'; killer++)//利用for循环分别把a/b/c/d四个人的assci码值赋给killer,从a开始依次判断,将a/b/c/d四个人都作为凶手进行判断
	{
		if ((killer!='a') + (killer=='c') + (killer=='d') + (killer!='d') == 3)//已知3个人说了真话,将a/b/c/d四个人说的话用代码描述出来
		{
			printf("%c\n", killer);
		}
	}
	return 0;
}

In Example 1, each person gives 2 conditions, only one of which is true, which means that the nesting of if judgment statements must be used to judge the ranking of 5 people. A loop statement must be used, so it is nested in a for loop. Nesting of if judgment statements. "Multiple for loops nested", the execution process is also nested.

Guess you like

Origin blog.csdn.net/m0_72000264/article/details/128592026