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
  •  | 
  •  

Pregunta

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();        
}
¿Fue útil?

Solución

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";

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top