How can I convert a string into a variable name in C#? - c#

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/

Related

How to display 2 values in a textbox?

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

How do I make random numbers follow certain custom rules?

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.

In C#, how can i get a label to display multiple results without using additional labels?

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.

How to check if there is multiple similar MAX value in Array

I have code which consists of Array in doubles, but right now I am trying to check how to detect if there is two similar MAX in the array. The number MAX that I have set is 100. So if there is two or more 100, I would like to display output: Multiple MAX value. Hence I thought of using IF-ELSE, but I am not sure on how to check for Multiple MAX value.
This is my code:
double num1 = 100;
double num2 = 100;
double num3 = 70;
double num4 = 65;
double[] array1 = { num1, num2, num3, num4 };
double text = array1.Max();
if()
{
}
else
{
}
You can use the Count extension method, Try this code:
if(array1.Count(x=>x == text) > 1){
//...
} else {
//...
}
int count=0;
bool maxreached=false;
for(int i=0;i<array1.Length;i++)
{
if(array1[i]==text)
count++;
if(count>1)
{
maxreached=true;
break;
}
}
if(maxreached)
Console.WriteLine("Max value = "+ text +" found multiple times");

C# Keeps Rounding Numbers Up Producing inaccurate results

Ok so this is doing my head in, it keeps producing a slightly inaccurate result by rounding up the digits after the decimal. i need the exact value, not a rounded one!
So to start with take the following code:
int num1 = 10087;
int num2 = 9971;
int num3 = 9909;
int num4 = 9917;
int num5 = 9904;
double average = (num1 + num2 + num3 + num4 + num5) / 5;
double percentage = (10000 - average) / 100;
If this math is done on a calculator, the value of "percentage" is 0.424. But if it is run through the code the value gets rounded to 0.43 which is inaccurate. How can i stop this happening?
note: please do not question the 10000 number, i also need the result to be exactly the correct number (0.424) that is very important in this case!
cast your average calc to double first
int num1 = 10087;
int num2 = 9971;
int num3 = 9909;
int num4 = 9917;
int num5 = 9904;
double average = (double)(num1 + num2 + num3 + num4 + num5) / 5;
double percentage = (10000 - average) / 100;
Just add a "d" after the numbers...
int num1 = 10087;
int num2 = 9971;
int num3 = 9909;
int num4 = 9917;
int num5 = 9904;
double average = (num1 + num2 + num3 + num4 + num5) / 5d;
double percentage = (10000 - average) / 100d;
The d tells the compiler to make these numbers double precision floating point values instead of integers (you can also just add a decimal point). Without the "d" the numbers are integers and the computer performs integer arithmetic. This means that
9 / 5 = 1 instead of 1.8
Kindly read the msdn form it will help you to know the real reason
reference :- http://msdn.microsoft.com/en-us/library/3b1ff23f.aspx
In it they already say that
When you divide two integers, the result is always an integer
Here you divide two integer so it's result is also int.
You just need to type cast that's all as the other people give ans
As Ela Write your code will look like
int num1 = 10087;
int num2 = 9971;
int num3 = 9909;
int num4 = 9917;
int num5 = 9904;
double average = (double)(num1 + num2 + num3 + num4 + num5) / 5;
double percentage = (10000 - average) / 100;

Categories

Resources