how to make a random in a loop in C#

  • Thread starter Thread starter Noctosphere
  • Start date Start date
  • Views Views 9,279
  • Replies Replies 17

Noctosphere

Nova's Guardian
Member
Joined
Dec 30, 2013
Messages
7,904
Reaction score
22,686
Trophies
6
Age
33
Location
Biblically accurate Hell
XP
27,224
Country
Canada
Hello
So today i'Ve been given a homework and in this, I must create a code where it asks for a int number to the user, then generate that amount of random number between 0 and 99, and then categorize them in three category (between 0-33, 34-66, 67-99)
however, I've been told to not use random in a loop because I would have 100% of those number in the same category
I tryed and indeed, they're all 100% in the same category, always, each try, no matter what i do.
So, I have the loop, I have all the system required, but the opart where it generates a random number
can someone pelase help me??
Ofc, I'll quote this link in my program commentary so teatcher will know where I got my help

thanks
 
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            Random rnd = new Random();

            Console.WriteLine("Veuillez entrer un nombre entier : ");
            int nbRepetition = 0;
            string nbRepetitionEntree = "";
            nbRepetitionEntree = Console.ReadLine();
            while (int.TryParse(nbRepetitionEntree, out nbRepetition)==false)
            {
                Console.WriteLine("Nombre invalide, veuillez entrer un nombre entier : ");
                nbRepetitionEntree = Console.ReadLine();
            }
            int nbSection1 = 0;
            int nbSection2 = 0;
            int nbSection3 = 0;
            int nbAleatoire = 0;
            for (int i = 0; i < nbRepetition; i++)
            {
               
                if (nbAleatoire <= 0 && nbAleatoire >= 33)
                {
                    nbSection1++;
                }
                else if (nbAleatoire <= 34 && nbAleatoire >= 66)
                {
                    nbSection2++;
                }
                else
                {
                    nbSection3++;
                }
            }
            Console.WriteLine("Nombres entre 0 et 33 : " + nbSection1);
            Console.WriteLine("Nombres entre 34 et 66 : " + nbSection2);
            Console.WriteLine("Nombres entre 67 et 99 : " + nbSection3);

        }
    }
}

--------------------- MERGED ---------------------------

?
Code:
Random myRandom = new Random();
for (int i=0;i<30;i++){
      Console.Out.WriteLine(myRandom.Next(0,100));
}

Numbers I got:
Code:
3
32
31
88
36
46
65
72
91
59
60
5
42
59
40
57
26
73
78
14
20
40
34
79
2
66
84
43
3
36
i didnt learn that lane
Console.Out.Writeline

just Console.WriteLine

--------------------- MERGED ---------------------------

btw i rremoved the random number affectation because it didnt work, but it was between the for lane and the first if
 
  • Like
Reactions: Dr.Hacknik
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            Random rnd = new Random();

            Console.WriteLine("Veuillez entrer un nombre entier : ");
            int nbRepetition = 0;
            string nbRepetitionEntree = "";
            nbRepetitionEntree = Console.ReadLine();
            while (int.TryParse(nbRepetitionEntree, out nbRepetition)==false)
            {
                Console.WriteLine("Nombre invalide, veuillez entrer un nombre entier : ");
                nbRepetitionEntree = Console.ReadLine();
            }
            int nbSection1 = 0;
            int nbSection2 = 0;
            int nbSection3 = 0;
            int nbAleatoire = 0;
            for (int i = 0; i < nbRepetition; i++)
            {
              
                if (nbAleatoire <= 0 && nbAleatoire >= 33)
                {
                    nbSection1++;
                }
                else if (nbAleatoire <= 34 && nbAleatoire >= 66)
                {
                    nbSection2++;
                }
                else
                {
                    nbSection3++;
                }
            }
            Console.WriteLine("Nombres entre 0 et 33 : " + nbSection1);
            Console.WriteLine("Nombres entre 34 et 66 : " + nbSection2);
            Console.WriteLine("Nombres entre 67 et 99 : " + nbSection3);

        }
    }
}

--------------------- MERGED ---------------------------


i didnt learn that lane
Console.Out.Writeline

just Console.WriteLine

--------------------- MERGED ---------------------------

btw i rremoved the random number affectation because it didnt work, but it was between the for lane and the first if
https://stackoverflow.com/questions/1149131/why-does-console-out-writeline-exist
 
Console.Out.Writeline does the same thing as Console.WriteLine in this case.

The problem wasn't your random number generation, it was your "if" statements.
I've fixed your loop for you.
Code:
for (int i = 0; i < nbRepetition; i++)
{
   nbAleatoire = rnd.Next(0,100); // Generate a new random number 1 through 99
   if (nbAleatoire <= 33)
   {
      nbSection1++;
   }
   else if (nbAleatoire <= 66) // There is no need to check if it's greater than 33 again because if it was less than or equal to 33, this "if" statement would never happen because the last one would be true.
   {
      nbSection2++;
   }
   else
   {
      nbSection3++;
   }
}
Here is your old code and why your "if" statements are wrong.
Code:
if (nbAleatoire <= 0 && nbAleatoire >= 33) // The number will never be less than 0 and greater than 33 at the same time.
{
             nbSection1++;
}
else if (nbAleatoire <= 34 && nbAleatoire >= 66) // The number will never be less than 34 and greater than 66 at the same time
{
             nbSection2++;
}
else // Because neither of those will ever be true, it's always this result.
{
             nbSection3++;
}
sooo... It'S just a dumb mistake xD
 
maybe you guys can help me furthermore
I'm trying to convert a float to a string, using ToString function to get a percentage
But I always get 2 extra 0 before the dot
I can'T figure out where I made a mistake
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            Random rnd = new Random();

            Console.WriteLine("Veuillez entrer un nombre entier : ");
            int nbRepetition = 0;
            string nbRepetitionEntree = "";
            nbRepetitionEntree = Console.ReadLine();
            while (int.TryParse(nbRepetitionEntree, out nbRepetition)==false)
            {
                Console.WriteLine("Nombre invalide, veuillez entrer un nombre entier : ");
                nbRepetitionEntree = Console.ReadLine();
            }
            int nbSection1 = 0;
            int nbSection2 = 0;
            int nbSection3 = 0;
            int nbAleatoire = 0;
            for (int i = 0; i < nbRepetition; i++)//on m'a aidé http://gbatemp.net/threads/how-to-make-a-random-in-a-loop-in-c.482959/#post-7554192
            {
                nbAleatoire = rnd.Next(0, 100); // Generate a new random number 1 through 99
                if (nbAleatoire <= 33)
                {
                    nbSection1++;
                }
                else if (nbAleatoire <= 66) // There is no need to check if it's greater than 33 again because if it was less than or equal to 33, this "if" statement would never happen because the last one would be true.
                {
                    nbSection2++;
                }
                else
                {
                    nbSection3++;
                }
            }
            float sec1Pct = 0f;
            float sec2Pct = 0f;
            float sec3Pct = 0f;
            sec1Pct = nbSection1 / nbRepetition * 100;
            sec2Pct = nbSection2 / nbRepetition * 100;
            sec3Pct = nbSection3 / nbRepetition * 100;
            Console.WriteLine("Nombres entre 1 et 33 : " + nbSection1 + "  " + sec1Pct.ToString("##.0#%"));
            Console.WriteLine("Nombres entre 34 et 66 : " + nbSection2 + "  " + sec2Pct.ToString("##.0#%"));
            Console.WriteLine("Nombres entre 67 et 99 : " + nbSection3 + "  " + sec3Pct.ToString("##.0#%"));


        }
    }
}
 
Last edited by Noctosphere,
Code:
sec1Pct = nbSection1 / nbRepetition * 100;
In this line, you're dividing integers, so the answer will be an integer, a whole number. You need to cast one of the numbers as a float so it'll do float division and give you a float as the result.
Code:
sec1Pct = (float)nbSection1 / nbRepetition * 100;

Next, you're using a number format string as an argument for ToString.
Code:
sec1Pct.ToString("##.0#%")
I don't think you even know what you wrote here. Refer to this article for information about number format strings.
The percent sign in the format string will multiply the number by 100 before displaying it, so you don't need to multiply by 100 beforehand.
Code:
sec1Pct = (float)nbSection1 / nbRepetition;
oh it multiplies by 100?
i didnt know, i dont think it did that before, ill try

--------------------- MERGED ---------------------------

Code:
sec1Pct = nbSection1 / nbRepetition * 100;
In this line, you're dividing integers, so the answer will be an integer, a whole number. You need to cast one of the numbers as a float so it'll do float division and give you a float as the result.
Code:
sec1Pct = (float)nbSection1 / nbRepetition * 100;

Next, you're using a number format string as an argument for ToString.
Code:
sec1Pct.ToString("##.0#%")
I don't think you even know what you wrote here. Refer to this article for information about number format strings.
The percent sign in the format string will multiply the number by 100 before displaying it, so you don't need to multiply by 100 beforehand.
Code:
sec1Pct = (float)nbSection1 / nbRepetition;
alright, it works, but whenever I get another answer other than 100%, I get a .0%
When i get 100% by entering 1, I get 100.0%
but when I enter 2, I get 3 .0%
 
You didn't look at the article on format strings.
Code:
sec1Pct.ToString("##.0#%")
Because there's a zero in the format string, there will always be at least one decimal place shown.
Code:
sec1Pct.ToString("#.##%")
This is what you should use if you want the number to have up to two decimal places shown.


(On a side note, you may want to prevent users from entering 0 in your program for nbRepetition.)
yea ive read this article, in french but ive read it
i might change it to # but I guess i'll still have the same problem
when it'S supposed to show 50.0%, it shows .0%
 
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            Random rnd = new Random();

            Console.WriteLine("Veuillez entrer un nombre entier : ");
            int nbRepetition = 0;
            string nbRepetitionEntree = "";
            nbRepetitionEntree = Console.ReadLine();
            while (int.TryParse(nbRepetitionEntree, out nbRepetition) == false)
            {
                Console.WriteLine("Nombre invalide, veuillez entrer un nombre entier : ");
                nbRepetitionEntree = Console.ReadLine();
            }
            int nbSection1 = 0;
            int nbSection2 = 0;
            int nbSection3 = 0;
            int nbAleatoire = 0;
            for (int i = 0; i < nbRepetition; i++)//on m'a aidé http://gbatemp.net/threads/how-to-make-a-random-in-a-loop-in-c.482959/#post-7554192
            {
                nbAleatoire = rnd.Next(0, 100); // Generate a new random number 1 through 99
                if (nbAleatoire <= 33)
                {
                    nbSection1++;
                }
                else if (nbAleatoire <= 66) // There is no need to check if it's greater than 33 again because if it was less than or equal to 33, this "if" statement would never happen because the last one would be true.
                {
                    nbSection2++;
                }
                else
                {
                    nbSection3++;
                }
            }
            float sec1Pct = 0f;
            float sec2Pct = 0f;
            float sec3Pct = 0f;
            sec1Pct = nbSection1 / nbRepetition;
            sec2Pct = nbSection2 / nbRepetition;
            sec3Pct = nbSection3 / nbRepetition;
            Console.WriteLine("Nombres entre 1 et 33 : " + nbSection1 + "  " + sec1Pct.ToString("##.##%"));
            Console.WriteLine("Nombres entre 34 et 66 : " + nbSection2 + "  " + sec2Pct.ToString("##.##%"));
            Console.WriteLine("Nombres entre 67 et 99 : " + nbSection3 + "  " + sec3Pct.ToString("##.##%"));


        }
    }
}
 
Amusing that you cited a forum post in the comments.

Anyway I am sitting here thinking this looks like classic introduce you to how to adapt your program territory a la fizzbuzz



Then trying to imagine what the obvious expansions will be, guessing more than 99 numbers and all of a sudden a few different categories or overlapping ones. You may also be asked to translate it to another language and having to pull all the strings out of that to translate might be seen as bad form but don't worry about that one too much yet.

Also, and this is why my haziness with c# will come to the fore, do you not have to exit the program properly? Most starting to program courses will try to drill that into you for a reason.
 
Amusing that you cited a forum post in the comments.

Anyway I am sitting here thinking this looks like classic introduce you to how to adapt your program territory a la fizzbuzz



Then trying to imagine what the obvious expansions will be, guessing more than 99 numbers and all of a sudden a few different categories or overlapping ones. You may also be asked to translate it to another language and having to pull all the strings out of that to translate might be seen as bad form but don't worry about that one too much yet.

Also, and this is why my haziness with c# will come to the fore, do you not have to exit the program properly? Most starting to program courses will try to drill that into you for a reason.

not sure to understand what you mean
 
The way the program you have now will do what you set out to do. However in real life someone will have another idea about what to do next and you get to implement it, or perhaps you get to implement it on someone else's code that is no longer with the company (making new things is easy and you can get any intern to do that, the ability to be repairing and improving old things is what means you still keep your job when everybody else is being made redundant.

The video above explains the general idea of why you want to program that way all far more clearly but the next step would be something like to change the numbers to between 0 and 133 or something but keep the 33 ranges for groupings (basically another group added) which is fine as it is just another few lines of code, however if you had kicked it to a variable you declared at the top it would be far easier. If instead of just another group I had asked to go to 1000 in groups of 33 you would be there for ages, or at best playing with a spreadsheet to do it for you. Another might be 1000 groups of 33 and another check to tell whether the numbers are odd or even.
I am probably jumping the gun though, bad habit of mine in threads like these. On the other hand if in the next lesson, or the lesson after you get asked that you will be able to sit there with a knowing smile.

In C you would do a return 0 or a proper exit command, however I am not sure for C# and the quick search I did before that did not reveal much more. Not so important for this as the entire functionality (give or take the random nature of it) is there and easily testable, for bigger programs the fact it did not exit cleanly (and maybe crashed instead) is your first clue something is wrong.
 

Site & Scene News

Popular threads in this forum