I have four text box A ,B,C and D.
Textbox A and B is user input field for example txtA = 250 ; txtB =300;
based on formula ((B-A/A)*100) i found value for C (%). After find the txtC (%20)value i have to find txtD.
To find out txtD, i have set of pre defined value to find txtD.
for example
if the % <10 then txtD=1
10-20 then txtD=2
20-30 then txtD=3 like wise until 100 %
. I am not sure whats the best approach to achieve this. i am just wondering create percentage table and handle or using switch statement is the best approach.
Why isn't it possible using simple if..else blocks?
Switch..Case is not appropriate when comparing range of values..
int D = (0.2 * C);
If (D < 10) {
txtD=2
}
elseif (D > 10 && D < 20){
txtD=3
}
elseif (D > 20 && D < 30){
txtD=4
}
..
Related
I have 2 textboxes on my form for which I'm trying to restrict the input. Here is a more detailed description of what I'm trying to do:
Code a method named IsValidData that checks that the Operand 1 and Operand 2 text boxes contain a decimal value between 0 and 1,000,000 (non-inclusive) and that the Operator text box contains a valid operator.
I know the way that I did this is wrong but I'm not sure how to fix it. The way I thought of it when writing the if statement is this:
check to make sure the value is >0 AND <=100 for the input in the txtOperand1 textbox and then did the same for the other textbox. Can someone please give suggestions on what I'm doing wrong? Thanks.
double operand1 = Convert.ToDouble(txtOperand1.Text);
double operand2 = Convert.ToDouble(txtOperand2);
if ((operand1 > 0 && operand1 <= 100) &&
(operand2 > 0 && operand2 <= 100))
return true;
something like this?
return decimal.TryParse(txt.Text, out decimal val) && (val > 0m & val < 1000000m)
Because I am writing software which generates SQL with a potentially large number of parameters and records that SQL onto disk, I have an uncommon requirement (perhaps more a curiosity): Generate the shortest possible unique parameter names.
Parameter names follow identifier naming rules which are usually:
First character is alphabetic
Subsequent characters can be alphanumeric or certain other characters, such as an underscore.
Almost anything can be used if quoted (ignored -- a quoted identifier is at least three characters total, e.g. [_])
The SQL generation code knows how many identifiers there are total, so names can be generated based on an integer.
This ended up being more difficult than I anticipated, and the solution less elegant.
I hard-coded invalid values (starting with 0) because they are few and every attempt I made to derive them ended up complicated and slow. I would appreciate ideas on how to make this more elegant. I'll post on CodeReview as well.
Most databases support fewer than 2^16 parameters (a ridiculous number to actually use), but in handling numbers larger than 35027 (also ridiculous) the numbers worked out such that 1 million was a good forced stopping point.
public static String intToDatabaseIdentifier(int number)
{
if(number < 0 || number > 1000000)
throw new ArgumentOutOfRangeException("number");
if(number > 25 && number <= 25 + 10) // Skip 0-9 (modified base 36)
number += 10;
if(number > 971 && number <= 971 + 360) // Skip 0a-09 (modified base 36)
number += 360;
if(number > 35027 && number <= 35027 + 12960) // Skip 0aa-099 (modified base 36)
number += 12960;
var stack = new Stack<char>();
// Base 36 starting with letters rather than numbers
const string characters = "abcdefghijklmnopqrstuvwxyz0123456789";
while(number >= 0) {
stack.Push(characters[number % 36]);
number = number / 36 - 1;
}
return new String(stack.ToArray());
}
Results starting with 0:
a b c d e f g h i j k l m n o p q r s t u v w x y z
aa ab ac ad ae af ag ah ai aj aa ab ac ad ae af ag ah ai aj ak al am an ao
ap aq ar as at au av aw ax ay az a0 a1...
Code above produces collisions. Fixed code without collisions and magic numbers.
public static String intToDatabaseIdentifier(int number)
{
const string abcFirst = "abcdefghijklmnopqrstuvwxyz";
const string abcFull = "abcdefghijklmnopqrstuvwxyz0123456789";
if (number < 0 || number > 1000000)
throw new ArgumentOutOfRangeException("number");
var stack = new Stack<char>();
//Get first symbol. We will later reverse string. So last - will be first.
stack.Push(abcFirst[number % abcFirst.Length]);
number = number / abcFirst.Length;
//Collect remaining part
while (number > 0)
{
int index = (number - 1) % abcFull.Length;
stack.Push(abcFull[index]);
number = (number - index) / abcFull.Length;
}
//Reversing to guarantee first non numeric.
return new String(stack.Reverse().ToArray());
}
Timur Mannapov's answer produces results similar to some of my other attempts (except his results don't have the problems noted in comments) in that the progression is not what one would expect, e.g. aa, ba, ca instead of aa, ab, ac:
(call with String.Concat(ToParamName(i)))
// Starts with aa, ba, ba... instead of a, b, c. Probably wouldn't be hard
// to fix but I abandoned this method because it's annoying to call using
// string.Concat(...)
public static IEnumerable<char> ToParamName(int number) {
const string characters = "abcdefghijklmnopqrstuvwxyz0123456789";
yield return characters[number % 26];
number = number / 26;
do {
yield return characters[number % 36];
number = number / 36 - 1;
} while(number >= 0);
}
// Starts with a, b, c...aa, ba, ba but has collisions starting around 960
public static IEnumerable<char> ToParamName(int number) {
const string characters = "abcdefghijklmnopqrstuvwxyz0123456789";
yield return characters[number % 26];
number = number / 26;
while(number > 0) {
yield return characters[number % 36];
number = number / 36 - 1;
}
}
I prefer having the results returned in a more natural order like a..z, aa, ab, ac...a9 (hey, I didn't claim I was being purely practical), but I forgot to mention that in the original post. Timur's answer covers all the original requirements, so I'll mark it correct.
I'll +1 an answer that produces results as described.
This question already has answers here:
Program to find prime numbers
(28 answers)
Closed 6 years ago.
This particular question does not involve loops and most of the answers I have seen involve loops. This is a challenge from one of the books I am reading. No, I'm not a student (38 years old) I'm actually switching careers, so I've decided to start learning how to program. The book I am reading is called "Introduction to C# / Joes 2 Pros".
Here's the code I have so far. I know there is more than likely a better way to do this using things I probably don't have a good grasp on. For example, I know what a "bool" is, but just haven't used it in any of my coding yet. Therefore, it's difficult to implement it.
int myChoice;
Console.Write("Please enter a number: ");
myChoice = int.Parse(Console.ReadLine());
if (myChoice >= 1 && myChoice % myChoice == 0)
{
Console.WriteLine("That's correct, {0} is a prime number.", myChoice);
}
else
{
Console.WriteLine("That is not a prime number.");
}
Console.ReadLine();
OK, as you can see the program asks for the user to enter a number. As determined by the if statement, if the number is greater than or equal to 1 AND the number is divisible by itself with no remainder, the statement is true.
I know there is a much better way of finding out if the number entered is a prime, but I just can't figure out what it is. The program does what I expect it to do except figuring out if the number is prime.
Just a bit of background here. What you are seeing on the screen is just about the extent of my knowledge of C#. Beyond what you see, I'm probably lost.
Any suggestions?
There is another very challenging requirement to test for prime, it must not divide by any other numbers. For example 4 is greater than zero and 4 % 4 = 0. But 4 is not a prime, it is equal to 2x2.
Testing for prime is rather difficult. Most starting programming books want you to experiment with the Sieve of Eratosthenes, which is an old way to determine if a number is a prime. The wiki page proposes an algorithm to implement for this. Basically you generate numbers from 1 to 100 in an array and remove those who are not prime, leaving you all primes from 1 to 100.
If your number n is small, it is simple to test all numbers less than sqrt(n) as divisors; if none of them divide n, then n is prime:
function isPrime(n)
d := 2
while d * d <= n
if n % d == 0
return Composite
d := d + 1
return Prime
For larger numbers, a reasonable test of primality is the Miller-Rabin test; it can be fooled (falsely proclaim that a composite number is prime) but with very low likelihood. Start with a strong pseudoprime test:
function isStrongPseudoprime(n, a)
d := n - 1; s := 0
while d is even
d := d / 2; s := s + 1
t := powerMod(a, d, n)
if t == 1 return ProbablyPrime
while s > 0
if t == n - 1
return ProbablyPrime
t := (t * t) % n
s := s - 1
return DefinitelyComposite
Each a for which the function returns ProbablyPrime is a witness to the primality of n; test enough of them and you gain some confidence that n is actually prime:
function isPrime(n)
for i from 1 to k
a := randint(2 .. n-1)
if isStrongPseudoprime(n, a) == DefinitelyComposite
return DefinitelyComposite
return ProbablyPrime
Variable k is the number of trials you want to perform; somewhere between 10 and 25 is typically a reasonable value. The powerMod(b,e,m) function returns b ^ e (mod m). If your language doesn't provide that function, you can efficiently calculate it like this:
function powerMod(b, e, m)
x := 1
while e > 0
if e % 2 == 1
x := (b * x) % m
b := (b * b) % m
e := floor(e / 2)
return x
If you're interested in the math behind this test, I modestly recommend the essay Programming with Prime Numbers at my blog.
Given a method of the bool data type that takes in an int variable, what is a single line of code that would determine if the int is an exponent of 2 or 2^n.....2,4,8,16,32 etc. I know of a way using a while loop and if statements, but I'm looking for it to be on one line.
From Bit Twiddling Hacks:
uint v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v != 0) && ((v & (v - 1)) == 0);
Just check if the log (base 2) of the number is an integer.
In one line of C#:
Math.Log(x, 2) % 1 == 0
Bitwise operations are more fun, but lord have mercy on whomever has to maintain that code.
bool powerOfTwo = (unchecked(n & (n-1)) == 0) && (n != 0)
bool answer = ((n & ~(n-1)) == n && n!=0);
This passes all the basic tests I threw at it.
It seems good.
When I try to take the N th root of a small number using C# I get a wrong number.
For example, when I try to take the third root of 1.07, I get 1, which is clearly not true.
Here is the exact code I am using to get the third root.
MessageBox.Show(Math.Pow(1.07,(1/3)).toString());
How do I solve this problem?
I would guess that this is a floating point arithmetic issue, but I don't know how to handle it.
C# is treating the 1 and the 3 as integers, you need to do the following:
Math.Pow(1.07,(1d/3d))
or
Math.Pow(1.07,(1.0/3.0))
It is actually interesting because the implicit widening conversion makes you make a mistake.
I'm pretty sure the "exact code" you give doesn't compile.
MessageBox.Show(Math.Pow(1.07,(1/3).toString()));
The call to toString is at the wrong nesting level, needs to be ToString, and (1/3) is integer division, which is probably the real problem you're having. (1/3) is 0 and anything to the zeroth power is 1. You need to use (1.0/3.0) or (1d/3d) or ...
First things first: if that's the exact code you're using, there's likely something wrong with your compiler :-)
MessageBox.Show(Math.Pow(1.07,(1/3).toString()));
will evaluate (1/3).toString() first then try and raise 1.07 to the power of that string.
I think you mean:
MessageBox.Show(Math.Pow(1.07,(1/3)).ToString());
As to the problem, (1/3) is being treated as an integer division returning 0 and n0 is 1 for all values of n.
You need to force it to a floating point division with something like 1.0/3.0.
This may help in case you have a real nth root precision problem, but my experiance is that the builtin Math.Pow(double, int) is more precise:
private static decimal NthRoot(decimal baseValue, int N)
{
if (N == 1)
return baseValue;
decimal deltaX;
decimal x = 1M;
do
{
deltaX = (baseValue / Pow(x, N - 1) - x) / N;
x = x + deltaX;
} while (Math.Abs(deltaX) > 0);
return x;
}
private static decimal Pow(decimal a, int b)
{
if (b == 0) return 1;
if (a == 0) return 0;
if (b == 1) return a;
if (b % 2 == 0)
return Pow(a * a, b / 2);
else if (b % 2 == 1)
return a * Pow(a * a, b / 2);
return 0;
}