[c#]随机数字生成器失败

发布时间: 2017/2/26 0:47:16
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我要循环回从一开始如果拿数量不正确的程序是怎么来的?不知道我做错了。我试过 if s, do while s, while s,和 if else s:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayProblms
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Guess a number between 1 and 10: ");
            RandomNumberGenerator();
            Console.ReadLine();
        }

        public static void RandomNumberGenerator()
        {
            Random rand = new Random();
            int userValue = int.Parse(Console.ReadLine());
            int randValue = rand.Next(1, 11);
            int attempts = 0;

            if (userValue == randValue)
            {
                Console.WriteLine("You have guessed correctly!");
            }
            while (userValue != randValue)
            {
                Console.WriteLine("You have guessed incorrectly");
                attempts++;
                Console.WriteLine("You have made {0} incorrect guesses", attempts);
                break;
            }
        }
    }
}

解决方法 1:

我会用 do...while 继续要求用户输入新号码,直到他猜对了。

下面的示例︰

public static void RandomNumberGenerator()
{
    Random rand = new Random();

    int randValue = rand.Next(1, 11);
    int attempts = 0;

    // do...while cycle to ask user to enter new value each time the used has been wrong
    do
    {
        // read user input
        int userValue = int.Parse(Console.ReadLine());

        // if user guessed correct
        if (userValue == randValue)
        {
            Console.WriteLine("You have guessed correctly!");
            // go away from do...while loop
            // it will stop asking user and will exit from the method
            break;
        }

        // if user has been wrong
        Console.WriteLine("You have guessed incorrectly");
        // increment attempts count
        attempts++;
        Console.WriteLine("You have made {0} incorrect guesses", attempts);
    }
    // and repeat until user guessed correctly
    while(userValue != randValue)
}
赞助商