C# Console Application: Number Guessing Game Demo
Here's a C# console application demonstrating loops and conditional statements through a number guessing game:
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine('Welcome to the number guessing game!');
Random rand = new Random();
int secretNumber = rand.Next(1, 101);
int tries = 0;
while (tries < 5) {
Console.Write('Guess a number between 1 and 100: ');
string input = Console.ReadLine();
int guess;
if (!int.TryParse(input, out guess)) {
Console.WriteLine('Invalid input, please enter a number.');
continue;
}
if (guess == secretNumber) {
Console.WriteLine('Congratulations, you guessed the secret number!');
return;
}
else if (guess < secretNumber) {
Console.WriteLine('Too low, try again.');
}
else {
Console.WriteLine('Too high, try again.');
}
tries++;
}
Console.WriteLine('Sorry, you ran out of tries. The secret number was {0}.', secretNumber);
}
}
This program generates a random number between 1 and 100 and prompts the user to guess. The user has 5 tries. Invalid input prompts the user to enter a valid number. Correct guess ends the game with a congratulatory message. Running out of tries reveals the secret number and ends the game.
原文地址: https://www.cveoy.top/t/topic/lPDn 著作权归作者所有。请勿转载和采集!