Home > Mobile >  Do something every number of percent
Do something every number of percent

Time:11-24

I wanted to make two commands that alternate exactly for the specified number of percentages.

How to do a command in while that will do only a few percent and if not do a different command.


I'm trying to create a program to which you give the total number of characters, how many characters it should return and the percentage that determines the ratio between two characters. e.g.

decimal r = (decimal)1 / 3 * 100 //r = 33,33...%
string output = "";

for (int i = 0; i < 10; i  )
{
  if (r) //go in only on r %
  {
    output  = "T "; //return 'T'
  }
  else
  {
    output  = "F "; //return 'F'
  }
}
Console.WriteLine(output);

Output:

F F T F F T F F T F

CodePudding user response:

If I understand correctly, you can use the remainder operator (%) to determing if the counter variable is an occurrence when you need to output "T" by using it with i and the value of numChars \ percent.

In other words, we can determine the occurrences by dividing the total number of characters by the percentage. This number tells us how often we need to output "T". If there are 100 characters, and we pass in 33%, then, since 100 / 33 == 3, we know that every 3rd character should be a "T".

For example:

public static void PrintResults(int numChars, int percentage)
{
    // In this implementation, 'percentage' is a whole number, like 33
    // Here we determine what the percentage of numChars is
    var percent = numChars * percentage / 100;

    // And now we can divide numChars by percent to find out
    // how often we need to display the alternate character
    var occurrence = numChars / percent;

    for(int i = 1; i <= numChars; i  )
    {
        // Here we use the remainder operator to determine if this is an 
        // occurrence where we should display the alternate character
        if (i % occurrence == 0) Console.Write("T ");
        else Console.Write("F ");
    }

    Console.WriteLine();
}

This would then be called like:

PrintResults(10, 33);

Which would output:

F F T F F T F F T F 
  • Related