开发者

C# print every third number!

Help needed to perform an output in C# console application.

I have a maximum number

int maxNr = 10;
int myValue = 1;

public void myMethod(){
int choice = int.Parse(Console.ReadLine());  // only 1 or 2 accepted.

//Only choice = 1 in displayed here.
if(choice == 1){
   while(myValue <= maxNr){
     Console.WriteLine(myValue);
     myValue = myValue + 3;
   }
}
}

Expected output: 1, 4, 7, 10 Next time the function is called the output should be: 3, 6, 9开发者_Go百科 2, 5, 8


myValue is stuck at 13 after the first call, so the code does not enter the loop the second time


Add this before the while loop:

if (myValue >= 10)
    myValue -= 10;

Edit:

1.If I understood you correctly, the expected output is:

1st call 1, 4, 7, 10.
2nd call: 3, 6, 9.
3rd call 2, 5, 8.

2.As some suggested, you should use for loop instead of while loops:

if (myValue >= maxNr)
    myValue -= maxNr;

for (; myValue <= maxNr; myValue += 3)
{
    Console.WriteLine(myValue);
}


for (i=0; i<n; i+=3) don't work for you?


Why not just use this?

for (int i = n; i <= maxNr; i = i+3) {
    Console.WriteLine(i);
}


myValue is not defined locally, so you need to set it to 0, when calling the method again, otherwise it would still be 10 and you do not enter the loop.


public void myMethod(){
int choice = int.Parse(Console.ReadLine());  // only 1 or 2 accepted.

int maxNr = 10;
int myValue = choice;

//Only choice = 1 in displayed here.
if(choice == 1){
   while(myValue <= maxNr){
     Console.WriteLine(myValue);
     myValue = myValue + 3;
   }
}
}

Reset your starting value each time.


You need to store myValue in a temporary variable and update it before exiting the method. As I understand your requirements the code to achieve the output is as given below,

static int maxNr = 10;
static int myValue = 1;

private static void Test()
{
    int lastValue = myValue;
    int choice = int.Parse(Console.ReadLine());  // only 1 or 2 accepted.

    //Only choice = 1 in displayed here.
    if (choice == 1)
    {
        while (myValue <= maxNr)
        {
            Console.WriteLine(myValue);
            myValue = myValue + 3;
        }
    }

    if (lastValue == 1)
    {
        myValue = lastValue + 3 - 1;
    }
    else
    {
        myValue = lastValue - 1;
    }
}


Method Call


static void Main(string[] args)
{
    Test();
    Test();
    Test();

Console.ReadLine();

}


Output
1
4
7
10

3
6
9

2
5
8

Note that the user needs to enter the value 1 at every function call.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜