c# program question - c#
if a textbox has 1 digit or a number that's larger than 31, the program will crash. how should I stop that?
so far, i have this code:
if (dd.Text.Length <= 1 || dd.Text > 31)
return;
obviously, that's wrong... :(
dd.Text > 31
The above code is comparing a string to an int. You should try:
int val = 0;
if (Int32.TryParse(dd.Text, out val))
{
if (val > 31) return;
}
dd.Text > 31
This line wont work. Try:
int.parse(dd.Text) > 31
Also if non numeric characters are entered it wont run, you might want to sanitise first.
What is obvious that You don't think about that what are You doing.
First of all You must to understand what basic types are available in C# and for what re they.
For now You should read about String, and Integer. The You will understand why that code do not work.
If You want to verify, that a text value form a textBox is between two numbers, first of all it need to be number. So You need to cast it...
Then You can operate on it and compare.
String myText = textBox.Text;
int myValue = -1;
if(Int32.tryPart(myText,myValue))
if(myValue > 31)
return;
Related
Efficiency of & 1 over % 2 [duplicate]
What is the fastest way to find if a number is even or odd?
It is pretty well known that static inline int is_odd_A(int x) { return x & 1; } is more efficient than static inline int is_odd_B(int x) { return x % 2; } But with the optimizer on, will is_odd_B be no different from is_odd_A? No — with gcc-4.2 -O2, we get, (in ARM assembly): _is_odd_A: and r0, r0, #1 bx lr _is_odd_B: mov r3, r0, lsr #31 add r0, r0, r3 and r0, r0, #1 rsb r0, r3, r0 bx lr We see that is_odd_B takes 3 more instructions than is_odd_A, the main reason is because ((-1) % 2) == -1 ((-1) & 1) == 1 However, all the following versions will generate the same code as is_odd_A: #include <stdbool.h> static inline bool is_odd_D(int x) { return x % 2; } // note the bool static inline int is_odd_E(int x) { return x % 2 != 0; } // note the != What does this mean? The optimizer is usually sophisticated enough that, for these simple stuff, the clearest code is enough to guarantee best efficiency.
Usual way to do it: int number = ...; if(number % 2) { odd } else { even } Alternative: int number = ...; if(number & 1) { odd } else { even } Tested on GCC 3.3.1 and 4.3.2, both have about the same speed (without compiler optimization) as both result in the and instruction (compiled on x86) - I know that using the div instruction for modulo would be much slower, thus I didn't test it at all.
if (x & 1) is true then it's odd, otherwise it's even.
bool is_odd = number & 1;
int i=5; if ( i%2 == 0 ) { // Even } else { // Odd }
int is_odd(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return !is_odd(n - 1); } Oh wait, you said fastest way, not funniest. My bad ;) Above function only works for positive numbers of course.
Check to see if the last bit is 1. int is_odd(int num) { return num & 1; }
If it's an integer, probably by just checking the least significant bit. Zero would be counted as even though.
The portable way is to use the modulus operator %: if (x % 2 == 0) // number is even If you know that you're only ever going to run on two's complement architectures, you can use a bitwise and: if (x & 0x01 == 0) // number is even Using the modulus operator can result in slower code relative to the bitwise and; however, I'd stick with it unless all of the following are true: You are failing to meet a hard performance requirement; You are executing x % 2 a lot (say in a tight loop that's being executed thousands of times); Profiling indicates that usage of the mod operator is the bottleneck; Profiling also indicates that using the bitwise-and relieves the bottleneck and allows you to meet the performance requirement.
Your question is not completely specified. Regardless, the answer is dependent on your compiler and the architecture of your machine. For example, are you on a machine using one's complement or two's complement signed number representations? I write my code to be correct first, clear second, concise third and fast last. Therefore, I would code this routine as follows: /* returns 0 if odd, 1 if even */ /* can use bool in C99 */ int IsEven(int n) { return n % 2 == 0; } This method is correct, it more clearly expresses the intent than testing the LSB, it's concise and, believe it or not, it is blazing fast. If and only if profiling told me that this method were a bottleneck in my application would I consider deviating from it.
Check the least significant bit: if (number & 0x01) { // It's odd } else { // It's even }
Can't you just look at the last digit and check if its even or odd if the input is in base 10? {1, 3, 5, 7, 9} is odd {0, 2, 4, 6, 8} is even Additional info: The OP states that a number is a given, so I went with that when constructing this answer. This also requires the number to be in base 10. This answer is mathematically correct by definition of even/odd in base 10. Depending on the use case, you have a mathematically consistent result just by checking the last digit. Note: If your input is already an int, just check the low bit of that. This answer is only useful for numbers represented as a sequence of digits. You could convert int->string to do this, but that would be much slower than n % 2 == 0. Checking the last digit does work for a string of digits in any even base, not just 10. For bases lower than 10, like base 8 (octal), 9 and 8 aren't possible digits, but the low digit being odd or even still determines whether the whole number is. For bases higher than 10, there will be extra possibilities, but you don't want to search a list anyway, just check if the digit as an integer is odd or even using the normal i % 2 == 0 or !=0 check. For ASCII hex using 'a' .. 'f' to represent digits values 10 through 15, the low bit of ASCII code does not represent odd or even, because 'a' == 0x61 (odd) but represents 10 aka 0xa (even). So you'd have to convert the hex digit to an integer, or do some bit-hack on the ASCII code to flip the low bit according to some other bit or condition.
Saving factorial in long integer
I am using the following code to get the Factorial, but it seems to be limited for me. private Int64 GetFactorial(Int64 value) { if (value <= 1) { return 1; } return value * GetFactorial(value - 1); } But it seems to only allow the values upto 65 on 66th value, it provides a 0 as a result and the result is negative too if the value is 65 or near. What can I do to allow more values to work with, and get result with having the System.StackOverflowException?
You may want to check out the BigInteger struct, as it allows integers of an arbitrarily-large size: http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx
Uint64 will get you more, not sure how many though.
c# forcing a numeric updown to only accept positive integers with try-parse
I've only been doing this a few days and I'm pretty confused. Everything else works fine, and the box only displays integers, but it still calculates with decimal values.
You should be able to do a int myInt = Convert.ToInt32(numBox.Value); numBox.Value is a decimal, but that code will cause it to get converted to an integer. Just know that IF you do get a decimal value back, it will round it up or down. EDIT: Aghilas Yakoub's solution might be better if you want only positive values. My solution will convert the decimal to an int, but it could still allow for negatives. Really what you should do is set your numBox.Minimum to 0 so it can't go below 0. EDIT 2: If you want to warn when the value is negative, try this: int myInt = Convert.ToInt32(numBox.Value); if (myInt < 0) { MessageBox.Show("Warning, your number must be 0 or greater"); } Do you want to warn if the value isn't a whole number (has decimal values)?
You can try with UInt32 result = 0; UInt32.TryParse("...", new CultureInfo(""), out result); if(result == 0) { Console.WriteLine("No parsing"); } else { Console.WriteLine("result={0}", result); }
A more elegant solution would be: If you have access to DevExpress controls, you should use a SpinEdit control. To limit its range from 0 to 999 (only integer number) set its: Properties.Mask.EditMask to "##0;" Properties.MaxValue to 999 Then the following line should work well without exceptions: int myInt = Convert.ToInt32(numBox.Value);
1000 digit number in C#
I am working on Project Euler and ran into an issue. I am unable to use a 1000 digit number and wanted to know if I am doing something wrong or am just going about this solution in the wrong way and if so what would be best approach be? C# namespace ToThePowerOf { class Program { static void Main(string[] args) { BigInteger n = 1; int x = 0; BigInteger [] number; number = new BigInteger[149194]; number[x] = 1; number[x + 1] = 1; x = 3; ; BigInteger check = 10000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 0000000000000000000000000000000 00000000000000000000000; for (int i = 99; i > 0; i--) { n = (n - 1) + (n - 2); number[x] = n; x++; if (n > check) { Console.WriteLine(x); } } } } }
I'm guessing the 'issue' you ran into (would be helpful to include error message) is that the compiler doesn't like the integer literal with 1000 digits so you can't initialise it with a very large integer literal. As others have noted, breaking the integer literal into multiple lines isn't valid either. The number[x] = 1; lines work because the compiler can handle the integer literal 1 and because we're assigning it to a BigInteger it uses BigInteger's implicit operator to convert it to a BigInteger. One simple method to get around your problem with the big integer literal is to use the BigInteger.Parse method to create your 1000 digit number. BigInteger check = BigInteger.Parse("10000....", CultureInfo.InvariantCulture); Another method could be to initialise it with a small int, then use maths to get to the number you want, as in Jon Skeet's answer.
There's no literal support for BigInteger in C#. So while using BigInteger isn't incorrect, you'll need to work out a different way of instantiating it - e.g. new BigInteger(10).Pow(1000).
Such a big literal isn't possible. Integer literals can be at most 64 bits. To get a large biginteger, you can either convert from string, or calculate the number instead of hardcoding it. In your case calculating it with BigInteger.Pow(10, digits) is the cleanest solution.
I'm still unsure on the BigInteger handling in C#, however on the Project Euler question you refer to. You can read the number in letter by letter from a text file and convert to an int. Then do the multiplications and checks. Not elegant but it works! See http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx for syntax ref.
I'm probably really late on this, but what I did was take every number and make it a separate object within an array. I then took the first 5 numbers of the array and multiplied them together and set them to a variable. If they were greater than the max, I set it to the max. I then went on to the next set for numbers 1-6 and did the same etc. I did get an out of range exception. In which case you use a try and get format until you receive this exception. If you want to see the code, I will edit my response, but to save you time on the array, if you still want to attempt this, I will give you the array. long[]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
I have a homework that I just can't figure out how to do. I'm not sure if the teacher wrote it wrong(he is a bad typer) or if there is a way to accomplish the task. I work in Visual C# 2010 Express - Console Application My task is to: Read a four digit integer, such as 5893, from the keyboard and display the digits separated from one another by a tab each. Use both integer division and modulus operator % to pick off each digit. If the user enters 4567, the output looks like: 4567 4 5 6 7 Sure I know how to separate the numbers by using \t as well as reading the input and displaying it to the user. But how am I supposed to 'pick off' each digit with division and the remainder operators? Maybe he means something else, but not sure. And another question... How do I make sure that what the user types in is a number and not a letter? Do I have to use Char.IsLetter, because I couldn't figure out how to use it on a parsed string. Example: string number1; int x; Console.Write("Please enter a number to calculate: "); number1 = Console.ReadLine(); x = Int32.Parse(number1); What method am I supposed to use and where do i put it in? Because now i only get an error and the application shuts down if I try to enter e letter.
The first question is really more about maths than programming. You know what the division and modulus operators do. Think about how you could use them to get the last (least significant) digit. Once you've done that you can apply a similar technique for the 2nd digit (tens) and then the same for hundreds and thousands and so on. You've already found Char.IsLetter, but there is also Char.IsDigit, which does what you want more directly. You can do this check for one character and what you have is a string of characters. Have a look at a foreach loop.
System.Int32.TryParse() might be a better choice when converting the String.
Yes, your assignment makes sense. Say you have an integer x = 4567. To pick out the digit at position A you would use: result = (int)((x / (A * 10)) % 10); The first part of this (x / (A * 10)) "shifts" x to the right. So a value of A = 1 would divide 4567 by 10 which results in 456.7. You then use the modulo operator "%" to pick out the unit part of that number. Finally you convert to an int to remove the fractional part.
Ok, I won't give the whole solution (after all, this is homework ;)). This code would check if there's four characters in input: string input; do { input = Console.ReadLine(); if (input.Length != 4) Console.WriteLine("You have to enter FOUR digits"); } while (input.Length != 4); This could be one way of checking the digits: bool isOk = true; foreach (char c in input.ToArray()) { if (!Char.IsDigit(c)) { Console.WriteLine("You have to enter four DIGITS"); isOk = false; break; } } This approach doesn't deal with math but you could do that just as well: int num = int.Parse(input); int tensOfThousands = num / 10000; int thousands = (num - tensOfThousands) / 1000; int lastDigit = num % 10; //the rest of the digits are up to you ;)
For everybody new to C#, the solution can be simpler. // Variables int number = 1234; int remainder; string s = ""; while (number > 0) { remainder = number % 10; s = remainder + "\n" + s; number /= 10; } Console.Write (s);