Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

c# - How to write a loop that exits after 3 even numbers are entered


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

that will let me enter numbers and will only stop if it encounters 3 even numbers in a loop?

Sure just use int.TryParse and the remainder operator

The premise is value % 2 == 0 will be true when even

var evenCount = 0;
while (evenCount < 3)
{
   Console.Write("Enter a number : ");
   if (int.TryParse(Console.ReadLine(), out var value) && value % 2 == 0)
      evenCount += 1;
}
Console.WriteLine("game over...");

Output

Enter a number : 1
Enter a number : 2
Enter a number : 3
Enter a number : 4
Enter a number : 5
Enter a number : 6
game over...

Additional Resources

TryParse(String, Int32)

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

Remainder Operator

The remainder operator % computes the remainder after dividing its left-hand operand by its right-hand operand.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...