In C# - How to convert boolean values 'true' and 'false to "PRIME" and "NOT PRIME" respectively

StackOverflow https://stackoverflow.com/questions/23593944

  •  20-07-2023
  •  | 
  •  

문제

This is my code so far, but I'm not sure how I can make the result textbox show only "PRIME" as the message to the user if the condition is "TRUE" (instead of showing just "TRUE") or show "NOT PRIME" as the message to the user if the result is not a prime number i.e. FALSE instead of showing "FALSE" . This is a scientific calculator that calculates prime numbers btw.

This is my first post here and I am a beginner so any help in the right direction would be appreciated. Cheers.

protected void calculatePrimeNumberButton_Click(object sender, EventArgs e)
{
    int num = int.Parse(numberPrimeTextBox.Text);
    int divider = 2;
    int maxDivider = (int)Math.Sqrt(num);
    bool prime = true;

    while (prime && (divider <= maxDivider))
    {
        if (num % divider == 0)
        {
            prime = false;
        }

        divider++;
    }

    resultPrimeNumberTextBox.Text = prime.ToString();        
}
도움이 되었습니까?

해결책

You could use the ternary operator:

resultPrimeNumberTextBox.Text = (prime) ? "PRIME" : "NOT PRIME";

This evaluates to

if (prime)
   resultPrimeNumberTextBox.Text = "PRIME";
else
   resultPrimeNumberTextBox.Text = "NOT PRIME";

다른 팁

You just need to do a simple check if prime set text box to "prime" else set it to "not prime". Don't do tostring on the boolean value.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top