簡體   English   中英

生成4個隨機數,總和為100,一個大於50

[英]Generate 4 random number whose sum is 100 and one is more than 50

我需要創建4個總和為100的int隨機數。其中一個大於50,並且大於其他整數。 我有這個:

int a=0, b=0,c=0,d=0;
int cem=100;
while (a+b+c+d=cem){
Random perc = new Random();
a = perc.Next(50, 100);
b = perc.Next(0, 50);
c = perc.Next(0, 50);
d = perc.Next(0, 50);
}

在編譯器中我得到2錯誤:

分配的左側必須是變量,索引器的屬性無法將類型'int'隱式轉換為'bool'

更換

while (a+b+c+d=cem){

while (a+b+c+d!=cem){

您正在使用賦值( = )而不是比較( == / != )。

除了關於編譯器錯誤消息的其他答案之外,您還應該移動該行

Random perc = new Random();

while循環的外部。 您只需要一個隨機數生成器,由於時間種子,在快速循環中重新生成它可能會產生相同的結果。

如果您考慮一下,四個隨機數之和為100意味着它們中只有三個是隨機數,而第四個是100減去其他三個數...因此,與其做循環,不如先生成一個數字,然后再生成一個帶有其余數的數字間隔,然后是第三個。

為什么要使用循環? 祝你好運:-)

(浪費了太多的CPU)

這就是我要開始做的事情;

class Program
{
    static void Main(string[] args)
    {
        int a = 0, b = 0, c = 0, d = 0;
        int cem = 100;
        Random perc = new Random();

        a = perc.Next(50, cem);
        cem -= a;

        b = perc.Next(0, cem);
        cem -= b;

        c = perc.Next(0, cem);
        cem -= c;

        d = cem;

        Console.WriteLine("{0} + {1} + {2} + {3} = {4}",a,b,c,d,a+b+c+d);

        Console.ReadKey(false);
    }
}
The left-hand side of an assignment must be a variable
Cannot implicitly convert type 'int' to 'bool'

while需要==,假設C#像C。==是相等測試,=是賦值。

(很明顯,這是為什么會導致第一條錯誤消息的原因。您可能需要考慮為什么它會解釋第二條錯誤消息,但是由於這樣做是一個很好的練習,因此我將不作解釋。)

這樣的事情怎么樣,循環次數會減少嗎?

int a = 0, b = 0, c = 0, d = 0;
int cem = 100;
Random perc = new Random();
a = perc.Next(50, cem);
b = perc.Next(0, cem - a);
c = perc.Next(0, cem - a - b);
d = cem - a - b - c;
class Program {
    void Main() {
        var random = new Random();

        // note it says one of them is more than 50
        // so the min value should be 51 not 50
        var a = random.Next(51, 100);

        // the rest of the number will be less than `a` 
        // because `a` is more than 50 so the max `remaining` 
        // will be is 49 (100 - 51)
        var remaining = 100 - a; 

        var b = random.Next(0, remaining);
        remaining -= b;

        var c = random.Next(0, remaining);
        remaining -= c;

        var d = remaining;

        Console.WriteLine("a: " + a);
        Console.WriteLine("b: " + b);
        Console.WriteLine("c: " + c);
        Console.WriteLine("d: " + d);
        Console.WriteLine("total: " + (a + b + c + d));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM