I am trying to display two random generated numbers in a text-box using visual studio.
This is what I have so far...
int RandomNumber(int min = 0, int max = 100)
{
Random random = new Random();
return random.Next(min, max);
}
int RandomNumber2(int min = 0, int max = 100)
{
Random random = new Random();
return random.Next(min, max);
}
txtQuestion.Enabled = true;
string num1 = Convert.ToString(RandomNumber());
string num2 = Convert.ToString(RandomNumber2());
txtQuestion.Text = ("{0} + {1} = ?", num1, num2);
However, the last line comes up with the error " cannot implicitly convert type '(string, string num1, string num2)' to 'string' "
How am I supposed to output these randomly generated numbers in the textbox?
Hi below is the edited code that works to how I needed it. Thanks for all the help :)
Random random1 = new Random();
I called the above function globally so I can refer to it every time I need a new random number. And below is how I used it in my function to call for two different random numbers and display them in a text-box.
int randomNumber1 = random1.Next(0, 10);
int randomNumber2 = random1.Next(0, 10);
string num1 = Convert.ToString(randomNumber1);
string num2 = Convert.ToString(randomNumber2);
txtQuestion.Text = string.Format ("{0} + {1} = ?", num1, num2);
As #John said, you are using a ValueTuple.
You can learn more about ValueTuple here or on the msdn. But the link I gave shows almost the same code as you wrote.
What you want to do is either to use string.Format :
txtQuestion.Text = string.Format("{0} + {1} = ?", num1, num2);
Or more concise with string interpolation :
txtQuestion.Text = $"{num1} + {num2} = ?";
And show the answer like this :
Random random = new Random();
int nextRandom() => random.Next(0, 100);
int num1 = nextRandom();
int num2 = nextRandom();
txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
// If you have a method that computes the result you can also call it inside
txtQuestion.Text = $"{num1} + {num2} = {SomeFunction(num1, num2)}";
To fix your random issue, you must create a random instance only once.
class MyClass
{
// Use the same instance of Random.
private Random _random = new Random();
public int RandomNumber()
{
return _random.Next(0, 100);
}
public void DisplayText()
{
int num1 = RandomNumber();
int num2 = RandomNumber();
txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
}
}
Related
I am trying to make a random Trinomial generator and I want the 2 random numbers to follow the trinomial rules (num1+num2=b)(num1*num2=c)
string a = "x²";
int b = new Random().Next(-50, 50);
int c = new Random().Next(-50, 50);
Console.WriteLine(a,b,c);
while (true)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
if ((num1 + num2 == b) && (num1 * num2 == c))
{
Console.WriteLine("Correct.");
break;
}
else
{
Console.WriteLine("Wrong. Try again");
}
}
I expect the numbers to be written down but they aren't. Also, I don't know how to make the random numbers follow these rules. PS - The random numbers are always the same, how do I change that?
Try this:
string a = "x²";
var randomGenerator = new Random();
int b = randomGenerator.Next(-50, 50);
int c = randomGenerator.Next(-50, 50);
Console.WriteLine("{0},{1},{2}", a, b, c);
bool isRunning = true;
while (isRunning)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
if ((num1 + num2 == b) && (num1 * num2 == c))
{
Console.WriteLine("Correct.");
isRunning = false;
}
else
{
Console.WriteLine("Wrong. Try again");
}
}
Console.ReadLine();
Explanation:
First of all the Random problem. Random generates numbers not really in a random way but calculates them. So since it is an algorithm it would work the same every try. To counter that, random seeds itself with the current time which then changes the output of the algorithm. In your case you create 2 random objects, but they will be generated so fast, that both actually seed with the same time, therefore calculating the same "random" numbers. That's why in my solution, we only create one Random object.
Second: If you just want to write one string to the console, jus concat the string and pass it as one parameter.
Here's my attempt at Charles' suggestion:
var rand = new Random();
string a = "x²";
int num1 = rand.Next(-50, 50);
int num2 = rand.Next(-50, 50);
int b = num1 + num2;
int c = num1 * num2;
Console.WriteLine($"{a}, {b}, {c}");
while (true)
{
int guess1 = int.Parse(Console.ReadLine());
int guess2 = int.Parse(Console.ReadLine());
if (guess1 == num1 && guess2 == num2)
{
break;
}
Console.WriteLine("Wrong. Try again");
}
Console.WriteLine("Correct.");
I've simplified the logic at the end a bit, but it should work the same.
I have four pre-defined input keywords. (e.g num1, num2, etc) Based on these keywords the user will define a formula in a textbox.
Example:
num1 + num2 * num3 * (num3-num1)
Since this input will be taken from a textbox it will be a string.
How can convert these keywords from string to the variable name and execute the formula in my code?
I didn't find any suitable answer for this in other threads.
Any help is appreciated. Thanks
Try out the DynamicExpresso nuget package - https://www.nuget.org/packages/DynamicExpresso.Core/
Then you can do something like:
var s = "num1 + num2 * num3 * (num3-num1)";
var interpreter = new Interpreter();
int num1 = 11;
int num2 = 12;
int num3 = 13;
var parameters = new[]
{
new Parameter("num1", num1),
new Parameter("num2", num2),
new Parameter("num3", num3)
};
var result = interpreter.Eval(s, parameters);
Console.WriteLine(result); // 323
You could do that by building a corresponding expression tree:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/
class Program
{
const int ROLLS = 51;
static void Main(string[] args)
{
Random r = new Random();
int sum = 0;
int[] dice1 = new int[ROLLS];
int[] dice2 = new int[ROLLS];
for (int roll = 0; roll <= 50; roll++)
{
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
Console.WriteLine("ROLL{0}: {1} + {2} = sum goes here", roll+1, dice1[roll]+1, dice2[roll]+1);
}
}
static int GenerateNum (Random r)
{
return r.Next(1, 7);
}
}
}
So what I have is two arrays to store two different int values that are randomly generated and what I am trying to achieve is the sum of these two randomly generated int values.
Upon execution it should display:
Roll 1: (random number) + (random number) = (sum of the two random numbers)
Just add the two together and store them in sum. Then present sum in the same manner you have presented the rest of the values in the output of the console:
dice1[roll] = GenerateNum(r);
dice2[roll] = GenerateNum(r);
sum = dice1[roll] + dice2[roll];
Console.WriteLine("ROLL{0}: {1} + {2} = {3}", roll + 1, dice1[roll], dice2[roll], sum);
My current code is as follows:
private void btnEXE_Click(object sender, EventArgs e)
{
int num1 = 0;
int num2 = 1;
int sum = 1;
do
{
sum = num1 + num2;
num1 = num2;
num2 = sum:
lblOUT.Text = Convert.ToString(num2);
while (sum <= 100);
}
When I run the program, it gives me only a result of 144.
What I need the program to do is list every result in between 0 and 100 then output every result into a single label.
BTW this is the Fibonacci sequence.
Any help would be greatly appreciated.
lblOUT.Text += Convert.ToString(num2) + Environment.NewLine;
That should be it
Among many solutions, a simple one would be to use StringBuilder:
StringBuilder sb = new StringBuilder();
do
{
...
sb.AppendFormat("{0} ", num2);
}
while (sum <= 100)
lblOUT.Text = sb.ToString();
You could also store the numbers in a list and use String.Join among other solutions.
I'm looking for some succinct, modern C# code to generate a random double number between 1.41421 and 3.14159. where the number should be [0-9]{1}.[0-9]{5} format.
I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.
You can easily define a method that returns a random number between two values:
private static readonly Random random = new Random();
private static double RandomNumberBetween(double minValue, double maxValue)
{
var next = random.NextDouble();
return minValue + (next * (maxValue - minValue));
}
You can then call this method with your desired values:
RandomNumberBetween(1.41421, 3.14159)
Use something like this.
Random random = new Random()
int r = random.Next(141421, 314160); //+1 as end is excluded.
Double result = (Double)r / 100000.00;
Random r = new Random();
var number = r.Next(141421, 314160) / 100000M;
Also you can't force decimal number to match your pattern. E.g. if you have 1.5 number it will not match 1.50000 format. So, you should format result as string:
string formattedNumber = number.ToString("0.00000");
I used this. I hope this helps.
Random Rnd = new Random();
double RndNum = (double)(Rnd.Next(Convert.ToInt32(LatRandMin.Value), Convert.ToInt32(LatRandMax.Value)))/1000000;
Check out the following link for ready-made implementations that should help:
MathNet.Numerics, Random Numbers and Probability Distributions
The extensive distributions are especially of interest, built on top of the Random Number Generators (MersenneTwister, etc.) directly derived from System.Random, all providing handy extension methods (e.g. NextFullRangeInt32, NextFullRangeInt64, NextDecimal, etc.). You can, of course, just use the default SystemRandomSource, which is simply System.Random embellished with the extension methods.
Oh, and you can create your RNG instances as thread safe if you need it.
Very handy indeed!
here my solution, it's not pretty but it works well
Random rnd = new Random();
double num = Convert.ToDouble(rnd.Next(1, 15) + "." + rnd.Next(1, 100));
Console.WriteLine(num);
Console.ReadKey();
JMH BJHBJHHJJ const int SIZE = 1;
int nnOfTosses,
headCount = 0, tailCount = 0;
Random tossResult = new Random();
do
{
Console.Write("Enter integer number (>=2) coin tosses or 0 to Exit: ");
if (!int.TryParse(Console.ReadLine(), out nnOfTosses))
{
Console.Write("Invalid input");
}
else
{
//***//////////////////
// To assign a random number to each element
const int ROWS = 3;
double[] scores = new double[ROWS];
Random rn = new Random();
// Populate 2D array with random values
for (int row = 0; row < ROWS; row++)
{
scores[row] = rn.NextDouble();
}
//***//////////////////////////
for (int i = 0; i < nnOfTosses; i++)
{
double[] tossResult = new double[i];
tossResult[i]= tossResult.nextDouble();
}
Console.Write("Number of Coin Tosses = " + nnOfTosses);
Console.Write("Fraction of Heads = ");
Console.Write("Fraction of Tails = ");
Console.Write("Longest run is ");
}
} while (nnOfTosses != 0);
Console.ReadLine();