Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

C# method rollDice

Hi need to write a program that Given a method rollDice() which simulates rolling a dice by returning a random value between 1 and 6, write a condition for the while loop in the code below so that it will end after a double 6 has been rolled (i.e. both dice have the value 6):need youre help.

    using System;
{
  class Program;
  {
        int a = 0;
        int b = 0;
        while ( a==6; b==6)
        {
          a = rollDice();
          b = rollDice();
          Console.WriteLine("{0} {1}",a,b);
        }
   }
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

EDIT: Changed the while to a do-while, as this will always execute once, regardless of the initial value of a or b. It's up to your preferences if you want to do it like this or with a while.

Next to that, I have changed the parameters of the while from while (a == 6 ; b ==6) to while(!(a == 6 && b ==6).

First of all, the ; in OP's post is syntactically incorrect, and won't work. It checks if a and/or b is 6 (depending on if the ; was supposed to be a || or a &&), and if it is, continues. That is the opposite of the desired effect, as OP wanted the loop to stop when both are 6.

while(!(a == 6 && b ==6) will check if both are 6, and if so it will stop the loop. If either is not 6, the loop will continue.

Try this:

int a;
int b;
//Do while because I'm assuming you always want to roll the dice at least once
    do 
    {
        a = rollDice();
        b = rollDice();
        Console.WriteLine("{0} {1}",a,b);
    } while (!(a == 6 && b == 6));

This will roll the dice until both are 6, as asked


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...