Farmer cross the river bug how to modify the original problem in the picture below

2023-01-25 21:04

Answer is not easy, answer useful please adopt, click on the right side of the answer to adopt!
The bug in this code occurs in the while loop of the main function. In this case, the ch2 variable is used to determine whether to continue the loop, but two getchar() functions are used to read the value of ch2. The second getchar() reads a carriage return, causing the loop to continue. This is a bug in the program.
To fix this bug, you should use a scanf() function when reading ch2's value and set it to read only one character, as follows :

scanf("%c", & ch2);

This avoids reading carriage returns and solves the problem of the loop running all the time.

Also, in this code, the srand(time(NULL)) function is used to initialize the random number generator. When running the program multiple times, doing so may result in the same random number each time the program runs. Therefore, it is recommended to add srand(time(NULL))

at the beginning of main

This ensures that random numbers are generated differently each time the program is run.

About the Author

Question Info

Publish Time
2023-01-25 21:04
Update Time
2023-01-25 21:04