I am looking at having a option to specify how often something should run, in terms of a percentage.
So I would have a textbox, that takes a number 0-100 to detirmine a percentage. I want to then take this number, and convert in into a matching random statement.
So for example:
textPercentage.text = "10"
would be changed to something like:
if (rnd.Next(1, 11) = 1)
{
do();
}
What is the best way to convert that numerical value to a matching random statement?
var i = int.Parse(textPercentage.Text);
if (rnd.Next(1, 101) <= i)
{
do();
}
You might want to use int.TryParse in stead of int.Parse to gracefully handle non digit inputs.
First get your value back into an int.
In WPF, this is easy because you just databind to an int property.
In WinForms you use the int.Parse method to get the value back: int.Parse(textBox.Text)
If you use the values 0-100 you can use something similar to your original code, as-is.
int value = int.Parse(textBox.Text);
if(rnd.Next(0, 100) < value)
{
DoSomething();
}
Otherwise, just add one to both the start and end values:
int value = int.Parse(textBox.Text);
if(rnd.Next(1, 101) <= value)
{
DoSomething();
}
The first one is simpler, so I'd go with it :)
Related
I converted decimal to binary number however i dont know how to represent on label. I have a list of numbers 0 and 1,Now, how do I display the information on labels.In fact, i dont know how to represent on label.
private void btnRun_Click(object sender, EventArgs e)
{
var decimaltoBinary = fnDecimalToBinary(Convert.ToInt32(txtenterNumber.Text));
}
private List<int> fnDecimalToBinary(int number)
{
int[] decimalNumbers = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
List<int> binaryNumbers = new List<int>();
int locDecimalArray = 0;
int sumNumber = 0;
for (int i = 0; i < decimalNumbers.Length; i++)
{
if (number < decimalNumbers[i])
{
sumNumber = number;
locDecimalArray = i - 1;
for (int j = locDecimalArray; j >= 0; j--)
{
if (sumNumber == 0)
{
binaryNumbers.Add(0);
return binaryNumbers;
}
else if (sumNumber >= decimalNumbers[j])
{
sumNumber = sumNumber - decimalNumbers[j];
binaryNumbers.Add(1);
}
else if (sumNumber < decimalNumbers[j])
{
binaryNumbers.Add(0);
}
}
return binaryNumbers;
}
}
return binaryNumbers;
}
It seems that you've received a comment that explains how you can convert your List<int> to the string value you need for the Label control. However, it seems to me that for the purposes of this exercise, you might benefit from some help with the decimal-to-binary conversion itself. There are already a number of similar questions on Stack Overflow dealing with this scenario (as you can guess, converting to binary text is a fairly common programming exercise), but of course none will start with your specific code, so I think it's worth writing yet another answer. :)
Basing the conversion on a pre-computed list of numeric values is not a terrible way to go, especially for the purposes of learning. But your version has a bunch of extra code that's just not necessary:
Your outer loop doesn't accomplish anything except verify that the number passed is within the range permitted by your pre-computed values. But this can be done as part of the conversion itself.
Furthermore, I'm not convinced that returning an empty list is really the best way to deal with invalid input. Throwing an exception would be more appropriate, as this forces the caller to deal with errors, and allows you to provide a textual message for display to the user.
The value 0 is always less than any of the digit values you've pre-computed, so there's no need to check for that explicitly. You really only need the if and a single else inside the inner loop.
Since you are the one populating the array, and since for loops are generally more readable when they start at 0 and increment the index as opposed to starting at the end and decrement, it seems to me that you would be better off writing the pre-computed values in reverse.
Entering numbers by hand is a pain and it seems to me that the method could be more flexible (i.e. support larger binary numbers) if you allowed the caller to pass the number of digits to produce, and used that to compute the values at run-time (though, if for performance reasons that's less desirable, pre-computing the largest digits that would be used and storing that in a static field, and then just using whatever subset of that you need, would be yet another suitable approach).
With those changes, you would get something like this:
private List<int> DecimalToBinary(int number, int digitCount)
{
// The number can't itself have more than 32 digits, so there's
// no point in allowing the caller to ask for more than that.
if (digitCount < 1 || digitCount > 32)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount must be between 1 and 32, inclusive");
}
long[] digitValues = Enumerable.Range(0, digitCount)
.Select(i => (long)Math.Pow(2, digitCount - i - 1)).ToArray();
List<int> binaryDigits = new List<int>(digitCount);
for (int i = 0; i < digitValues.Length; i++)
{
if (digitValues[i] <= number)
{
binaryDigits.Add(1);
number = (int)(number - digitValues[i]);
}
else
{
binaryDigits.Add(0);
}
}
if (number > 0)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount was not large number to accommodate the number");
}
return binaryDigits;
}
And here's an example of how you might use it:
private void button1_Click(object sender, EventArgs e)
{
int number;
if (!int.TryParse(textBox1.Text, out number))
{
MessageBox.Show("Could not convert user input to an int value");
return;
}
try
{
List<int> binaryDigits = DecimalToBinary(number, 8);
label3.Text = string.Join("", binaryDigits);
}
catch (ArgumentOutOfRangeException e1)
{
MessageBox.Show("Exception: " + e1.Message, "Could not convert to binary");
}
}
Now, the above example fits the design you originally had, just cleaned it up a bit. But the fact is, the computer already knows binary. That's how it stores numbers, and even if it didn't, C# includes operators that treat the numbers as binary (so if the computer didn't use binary, the run-time would be required to translate for you anyway). Given that, it's actually a lot easier to convert just by looking at the individual bits. For example:
private List<int> DecimalToBinary2(int number, int digitCount)
{
if (digitCount < 1 || digitCount > 32)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount must be between 1 and 32, inclusive");
}
if (number > Math.Pow(2, digitCount) - 1)
{
throw new ArgumentOutOfRangeException("digitCount",
"digitCount was not large number to accommodate the number");
}
List<int> binaryDigits = new List<int>(digitCount);
for (int i = digitCount - 1; i >= 0; i--)
{
binaryDigits.Add((number & (1 << i)) != 0 ? 1 : 0);
}
return binaryDigits;
}
The above simply starts at the highest possible binary digit (given the desired count of digits), and checks each individual digit in the provided number, using the "bit-shift" operator << and the logical bitwise "and" operator &. If you're not already familiar with binary arithmetic, shift operations, and these operators, this might seem like overkill. But it's actually a fundamental aspect of how computers work, worth knowing, and of course as shown above, can dramatically simplify code required to deal with binary data (to the point where parameter validation code takes up half the method :) ).
One last thing: this entire discussion ignores the fact that you're using a signed int value, rather than the unsigned uint type. Technically, this means your code really ought to be able to handle negative numbers as well. However, doing so is a bit trickier when you also want to deal with binary digit counts that are less than the natural width of the number in the numeric type (e.g. 32 bits for an int). Conversely, if you don't want to support negative numbers, you should really be using the uint type instead of int.
I figured that trying to address that particular complication would dramatically increase the complexity of this answer and take away from the more fundamental details that seemed worth conveying. So I've left that out. But I do encourage you to look more deeply into how computers represent numbers, and why negative numbers require more careful handling than the above code is doing.
I am trying to build a help function in my guess the number game, whereby the user gets the first digit of the number he/she has to guess. So if the generated number is 550, he will get the 5.
I have tried a lot of things, maybe one of you has an idea what is wrong?
public partial class Class3
{
public Class3()
{
double test = Convert.ToDouble(globalVariableNumber.number);
while (test > 10)
{
double firstDigit = test / 10;
test = Math.Round(test);
globalVariableNumber.helpMe = Convert.ToString(firstDigit);
}
}
}
Under the helpButton clicked I have:
private void helpButton_Click(object sender, EventArgs e)
{
label3.Text = globalVariableNumber.helpMe;
label3.AutoSize = true;
That is my latest try, I putted all of this in a custom class. In the main I putted the code to show what is in the helpMe string.
If you need more code please tell me
Why not ToString the number and use Substring to get the first character?
var number = 550;
var result = number.ToString().Substring(0, 1);
If for some reason you dont want to use string manipulation you could do this mathematically like this
var number = 550;
var result = Math.Floor(number / Math.Pow(10, Math.Floor(Math.Log10(number))));
What's wrong - you have an infinite while loop there. Math.Round(test) will leave the value of test unchanged after the first iteration.
You may have intended to use firstDigit as the variable controlling the loop.
Anyway, as suggested by others, you can set helpMe to the first digit by converting to a string and using the first character.
As an aside, you should consider supplying the number as a parameter and returning the helpMe string from the method. Your current approach is a little brittle.
The problem with your code is that you are doing the division and storing that in a separate variable, then you round the original value. That means that the original value only changes in the first iteration of the loop (and is only rounded, not divided), and unless that happens to make the loop condition false (i.e. for values between 10 and 10.5), the loop will never end.
Changes:
Use an int intead of a double, that gets you away from a whole bunch of potential precision problems.
Use the >= operator rather than >. If you get the value 10 then you want the loop to go on for another iteration to get a single digit.
You would use Math.Floor instead of Math.Round as you don't want the first digit to be rounded up, i.e. getting the first digit for 460 as 5. However, if you are using an integer then the division truncates the result, so there is no need to do any rounding at all.
Divide the value and store it back into the same variable.
Use the value after the loop, there is no point in updating it while you still have multiple digits in the variable.
Code:
int test = (int)globalVariableNumber.number;
while (test >= 10) {
test = test / 10;
}
globalVariableNumber.helpMe = test.ToString();
By using Math.Round(), in your example, you're rounding 5.5 to 6 (it's the even integer per the documentation). Use Math.Floor instead, this will drop the decimal point but give you the number you're expecting for this test.
i.e.
double test = Convert.ToDouble(globalVariableNumber.number);
while (test > 10)
{
test = Math.Floor(test / 10);
globalVariableNumber.helpMe = Convert.ToString(firstDigit);
}
Like #Sam Greenhalgh mentions, though, returning the first character of the number as a string will be cleaner, quicker and easier.
globalVariableNumber.helpMe = test >= 10
? test.ToString().SubString(0, 1)
: "Hint not possible, number is less than ten"
This assumes that helpMe is a string.
Per our discussion in the comments, you'd be better off doing it like this:
private void helpButton_Click(object sender, EventArgs e)
{
label3.Text = GetHelpText();
label3.AutoSize = true;
}
// Always good practice to name a method that returns something Get...
// Also good practice to give it a descriptive name.
private string GetHelpText()
{
return test >= 10 // The ?: operator just means if the first part is true...
? test.ToString().SubString(0, 1) // use this, otherwise...
: "Hint not possible, number is less than ten" // use this.
}
Well I enquired about checking if certain keywords can be found in an list and if they are all there the question is correct. Found here: Check if the string contains all inputs on the list
What I would like to also know is how many of the words are in the list, then divide it and get a percentage, so the user knows how accurately they answered each question.
public String KeyWords_Found()
{
int Return_Value = 0;
foreach (String s in KeyWords)
{
if (textBox1.Text.Contains(s))
{
Return_Value++;
}
}
int Holder = Return_Value / KeyWords.Count;
int Fixed = Holder * 100;
return Fixed + "%";
}
So what I want that code it do is check for all instances of keywords listed into the list KeyWords. Then get the percentage by dividing by the total amount of keywords and multiplying by 100. But it says that both values are 0 and i cant divide by 0. I'm not sure why they would be zero. Confused! Help!
You should first check, if KeyWords is empty or not
public String KeyWords_Found()
{
if (KeyWords.Count == 0)
return "0%";
// rest of the code
}
Alternatively you could use Linq instead of writing your own method:
int nOfOccurences = KeyWords.Where(k => textBox1.Text.Contains(k)).Count();
make sure you are using System.Linq; for that to work.
You'll still need to check for KeyWords.Count == 0 and compute the percentage yourself, though.
You should use floating point maths instead of integer maths in your calculations.
int i=100;
int a=51;
(i/a)==0 //true, integer division sucks for calculating percentages
((double)i/a)==0 //false, actually equals ~1.96
I want to formatting a column of sum value: for example I have 19240 I want it 192.40 I tried many way but nothing
dgw.Grid.Columns["Sum"].DefaultCellStyle.Format="0:00" // 192:40
dgw.Grid.Columns["Sum"].DefaultCellStyle.Format="n" // 19240.00
dgw.Grid.Columns["Sum"].DefaultCellStyle.Format="0.00" // 19240.00
dgw.Grid.Columns["Sum"].DefaultCellStyle.Format=string.Format("{0:0.##}") // Exception
I want all items in that column in datagrid view with the same format
edit : a way to do it:
I use this methode to get what I want
int _sum;
public int Sum
{
get { return _sum; }
set { _sum= value; }
}
public double SumAsdouble
{
get
{
if (_sum== 0)
return 0;
else
return Convert.ToDouble(_sum) / 100;
}
}
and I make hidden the Sum and show the SumAsdouble
and this work for me
What is the value in the cell?
It looks like it is 19240, which means that formatting it to 2DP will return 19240.00, as you are seeing. If you want 192.40, then you'll need to divide by 100 first - you'll not be able to do this with string formats.
I assume that you always want to have the last two digits to be decimal digits and that your number is always five digits long. Then you can use "000.00" or "%" as format string. Alternatively, you can devide your number by 100.
I'm trying to write a program in C# that takes in an int x and decides if it has exactly 7 digits. Right now I'm using x.toString().Length == 7 to check, but I noticed that if the number starts with 0, it automatically gets omitted and I get an incorrect answer (ie the program thinks the input length is less than 7)
Is there a way to fix this? Thanks in advance.
Edit: Sorry I should have mentioned, this was a program to collect and validate the format of ID numbers (so I didn't want something like 0000001 to default to 1) Thanks for the string input suggestion, I think I'm going to try that.
If you want to preserve the input formatting, you must not convert the input to an int. You must store it in a String.
You say your program takes an int. At that point you have already lost. You need to change that interface to accept String inputs.
If you don't care about leading zeros, you're really looking for 7 digits or less. You can check for:
x.toString().Length <= 7
or better:
x < 10000000
Maybe I'm wrong, but to me, 0000001 == 1, and 1 has one digit, not seven. So that's mathematically correct behaviour.
I think you could format it as a string:
int myInt=1;
myInt.ToString("0000000");
prints:
0000001.
so you could do:
if (myInt.ToString("0000000").Length==7)
You can simply write:
int input = 5;
if(input.ToString("0000000").Length == 7)
{
//do your stuff
}
No. It is perfectly valid for a numeric literal to have leading 0s, but a) many languages consider this to be an octal literal, and b) the leading 0s don't actually exist as part of the number. If you need a string then start with a string literal.
You should use string to check length count including 0.
Then I would like to ask "Why do you want to show 0000007? For What?"
You said you're asking for a int, but I suppose you're receiving it as string:
int i = 0;
string number = Console.ReadLine();
if (Int32.TryParse(number, out i))
{
//if (i.ToString().Length == 7) // you can try this too
if (i > 999999 && i < 10000000)
{
Console.WriteLine("Have exactly 7 digits");
}
else
{
Console.WriteLine("Doesn't have exactly 7 digits");
}
}
else
{
Console.WriteLine("Not an Int32 number");
}
This way you try to cast that received number as Int32 and, so, compare its length.
You can let the number be saved as an int with the omitted zeros. but then if you want the number displayed with the zeros then you can use an if statement and a while loop. for example,
Let's assume the values are stored in a numbers array and you need them to be stored as int so you can sort them but displayed as string so you can display with the leading zeros.
int[] numbers = new int[3];
numbers[0] = 001;
numbers[1] = 002;
numbers[2] = 123;
String displayed_Number;
for (int i = 0; i < numbers.Length; i++)
{
displayed_Number = numbers[i].ToString();
if (displayed_Number.Length == 3)
{
listBox.Items.Add(displayed_Number);
}
else if (displayed_Number.Length < 3)
{
while (displayed_Number.Length < 3)
{
displayed_Number = "0" + displayed_Number;
}
listBox.Items.Add(displayed_Number);
}
}
The output is 001 002 123
That way you can maintain the zeros in the numbers when displayed. and they can be stored as int in case you have to store them as int.