I just found very strange thing in my code. By mistake I have put as an index something like this:
int a = 1;
int b = 1;
Dictionary<int, SomeClass> dic = new Dictionary<int, SomeClass> ();
dic[a -+ b].Field = 0;
As you can see there is "-+" opperator that really works as "-".
Anyway the code was having good time, was compiling until I found it.
It is part of code in Unity3d for game that I am working on now.
The question is: is it normal? Or this is know bug in mono 2 and was fixed. I cannot find any info about it.
There's nothing strange about this, and there isn't a -+ operator. There's a unary + operator and a binary - operator. Just add parentheses and some spacing to make it clearer:
int a = 1;
int b = 1;
int c = a -+ b;
int d = a - (+b); // Same as above
Note that you can use +- as well, with the unary - operator and the binary + operator:
int e = a +- b;
int f = a + (-b); // Same as above
And while you can't use ++ or -- like this, because those really are separate operators, you can add a space:
int g = a + + b;
int h = a + (+b); // Same as above
int i = a - - b;
int j = a - (-b); // Same as above
You can also have multiple unary operators chained together, for real craziness:
int k = a +-+-+-+ b;
int l = a + (-(+(-(+(-(+b)))))); // Same as above
Related
hello im new to programing with c# and i wanted to re-create an old proyect i made in scratch but with c#
but i have several problems with the code i wrote.
int qny = 4;
int ADD = 1;
int B = 1;
string C = " ";
for (int i = 0; i < qny; i++) ;
{
int R = qny + ADD;
for (int i = 0; i < R; i++) ;
{
string C = string.Join(C, B);
}
int qny = qny - 1;
int B = B + 1;
}
Console.WriteLine(C);
the main problem is that i cant use the variables "qny","B" and "C" inside the "for". the only one that doesnt show an error message is the "ADD" variable
its suposed to write numbers like this
qny
result
2
112
3
111223
4
1111222334
errors:
Error CS0841 Cannot use local variable 'qny' before it is declared. A variable must be declared before it is used.
Error CS0136 A local variable named 'C' cannot be declared in this scope because it would give a different meaning to 'C', which is already used in a 'parent or current/child' scope to denote something else
Error CS0165 Use of unassigned local variable 'C'
Error CS0841 Cannot use local variable 'B' before it is declared.
Error CS0136 A local variable named 'qny' cannot be declared in this scope because it would give a different meaning to 'qny', which is already used in a 'parent or current/child' scope to denote something else
Error CS0136 A local variable named 'B' cannot be declared in this scope because it would give a different meaning to 'B', which is already used in a 'parent or current/child' scope to denote something else
Your for loops end with a semicolon, which ends the loop. The following code blocks are not treated as part of the loop body because of that. Additionally as aybe mentioned you use i for both loops which will update the same variable.
EDIT: As mentioned below you also shouldn't redeclare the variable C as it won't update the variable C at the top, same reason as to why you don't want to use i for both loops.
EDIT: Code below still has redeclared variables, check author's answer for updated code.
I suggest changing it to this:
int qny = 4;
int ADD = 1;
int B = 1;
string C = " ";
for (int i = 0; i < qny; i++)
{
int R = qny + ADD;
for (int j = 0; j < R; j++)
{
C = string.Join(C, B);
}
int qny = qny - 1;
int B = B + 1;
}
Console.WriteLine(C);
To avoid such errors in the future I would recommend checking out some tutorials on the basics of C#. I wish you good luck on your coding journey!
Thanks to the people that helped me. As someone suggested, I’ll check out some tutorials. The final code looks like this:
int qny = 4;
int ADD = 1;
int B = 1;
string C = " ";
for (int i = 0; i < qny; i++)
{
int R = qny + ADD;
for (int j = 0; j < R; j++)
{
C = string.Join(C, B);
}
qny = qny - 1;
B = B + 1;
}
Console.WriteLine(C);
I have a problem with calculate of ASCII value with exponent and modulus.
I want calculate ASCII value of "K" with RSA algorithm.
K in ascii value is 75
c = m^e mod n
= 75^41 mod 689
= 316
Then how to make it into source code in C#? I got error "cannot implicity convert type".
this my source code
int n = 689;
int e = 41;
int d = 137;
string value = "K";
for (int i = 0; i < value.Length; i++)
{
int c = (int)i;
c = Math.Pow(i,e);
}
Console.ReadLine();
Since 75^41 will overflow if cast to an int you have to do a little math trick. A*B mod N is equivalent to (A mod N) * (B mod N) mod N, so you just do the multiplication in a loop, taking the remainder each time:
public static int PowModN(int a, int b, int n)
{
a = a % n;
int c = 1;
for(int i=1; i <= b; i++)
c = (c*a % n);
return c;
}
and change your loop to:
for (int i = 0; i < value.Length; i++)
{
int c = (int)i;
c = PowModN(i,e,n);
}
string value = "K";
// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
Once you get the array out put you can set it to a variable and do whatever math you need to do.
The output of Math.Pow is a double, and takes two floats as arguments. At the very least, cast the output of Math.Pow(i,e) to be an int, like so:
c = (int)Math.Pow(i,e)
This is one of the worst things about C#, imo. Not sure why it doesn't innately support integer exponentiation.
What type is i? It might need to be casted to doubles as well.
For the long time I thought I get it, and I was going to create some puzzles to learn some of my „students“ on the topic of operator precedence in c#.
But it came out that I still don't get it right.
Puzzles:
What’s the output here?
int a = 0;
int x = --a + a++;
Console.WriteLine(x);
Console.WriteLine(a);
Output:
-2
0
All clear here, I expected this
Next, the problem one:
int b = 0;
int y = b-- + b++;
Console.WriteLine(y);
Console.WriteLine(b);
Output:
-1
0
Well, here I also expected y to be -2… Now I’m trying to apply operator precedence rules and order of evaluation, and not sure I explained it to myself.
Read this post again few times today, but still don’t quite get it why is the result here -1?
Can someone help with how is the second result evaluated. why and how is it different than the first one?
b-- is post-decrement. So:
b-- returns zero and subtracts 1 from b, leaving -1 in b.
b++ returns the -1 from the last step and adds 1, leaving 0 in b.
Final result of the addition: -1.
Do what the compiler does: break it down slowly and surely into equivalent programs.
int b = 0;
int y = b-- + b++;
is equivalent to
int b, y;
b = 0;
y = b-- + b++;
is equivalent to
int b, y;
b = 0;
int leftAddend = b--;
int rightAddend = b++;
y = leftAddend + rightAddend;
is equivalent to
int b, y;
b = 0;
int originalb1 = b;
int newb1 = originalb1 - 1;
b = newb1;
int leftAddend = originalb1;
int originalb2 = b;
int newb2 = originalb2 + 1;
b = newb2;
int rightAddend = newb2;
y = leftAddend + rightAddend;
And now annotate each with its value:
int b, y;
b = 0; // b is now 0
int originalb1 = b; // originalb1 is now 0
int newb1 = originalb1 - 1; // newb1 is now -1
b = newb1; // b is now -1
int leftAddend = originalb1; // leftAddend is now 0
int originalb2 = b; // originalb2 is now -1
int newb2 = originalb2 + 1; // newb2 is now 0
b = newb2; // b is now 0
int rightAddend = originalb2;// rightAddend is now -1
y = leftAddend + rightAddend;// y is now -1
This is precisely how the compiler deals with this situation; the compiler is just a bit more clever about optimizing away the temporaries. Analyzing expressions gets easy if you just break it down into simpler steps.
int b = 0;
int y = b-- + b++;
Break it down by step:
y = b--
Here, y is set to b (0), then b is decremented to -1.
+ b++
Here, y (0) is added to b (decremented to -1 in prev step) equaling -1, then b is incremented to zero. Output:
-1 0
Postfix --/++ returns the original value of the variable. So:
With your example b-- + b++:
b-- means decrement b, return the original value. So b = b - 1, b is now -1, and the value of the expression is 0.
b++ means increment b, return the original value. So b = b + 1, b is now 0, and the value of the expression is -1.
Then, 0 + -1 == -1. This is y. b is still 0.
This question has been answered, but I wanted to state the answer another way.
int b = 0;
int y = b-- + b++;
The expression b-- evaluates to 0 (the original value of b) and has the side effect (applied after evaluation) of decrementing b to -1.
The expression b++ evaluates to -1 (because of the previous side effect) and has the side effect (applied after evaluation) of incrementing b to 0.
This leaves the expression 0 + -1 which is -1.
I have a number, for example 1234567897865; how do I max it out and create 99999999999999 ?
I did this this way:
int len = ItemNo.ToString().Length;
String maxNumString = "";
for (int i = 0; i < len; i++)
{
maxNumString += "9";
}
long maxNumber = long.Parse(maxNumString);
what would be the better, proper and shorter way to approach this task?
var x = 1234567897865;
return Math.Pow(10, Math.Ceiling(Math.Log10(x+1e-6))) - 1;
To expand on comments below, if this problem was expressed in hex or binary, it could be done very simply using shift operators
i.e., "I have a number, in hex,, for example 3A67FD5C; how do I max it out and create FFFFFFFF?"
I'd have to play with this to make sure it works exactly, but it would be something like this:
var x = 0x3A67FD5C;
var p = 0;
while((x=x>>1)>0) p++; // count how many binary values are in the number
return (1L << 4*(1+p/4)) - 1; // using left shift, generate 2 to
// that power and subtract one
long maxNumber = long.Parse(new String('9', ItemNo.ToString().Length));
Try this:
int v = 1;
do {
v = v * 10;
} while (v <= number);
return v - 1;
int numDigits = (int)Math.Ceiling(Math.Log10(number));
int result = (int)(Math.Pow(10, numDigits) - 1)
I don't have a compiler available at the moment, so some additional string/double conversions may need to happen here.
I'm having some trouble with this problem in Project Euler.
Here's what the question asks:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
My code so far: EDITED WITH NEW CODE THAT STILL DOESN'T WORK.
static void Main(string[] args)
{
int a = 1;
int b = 2;
int Container = 0;
int Sum = 0;
while (b < 4000000)
{
if (a % 2 == 0)
{
Container += a;
}
Sum = a + b;
a = b;
b = Sum;
}
Container += b;
Console.WriteLine(Container.ToString());
Console.ReadLine();
}
One of the fun feature in C# is the "yield" keyword, which is very useful for this kind of thing:
IEnumerable<int> Fibonacci()
{
int n1 = 0;
int n2 = 1;
yield return 1;
while (true)
{
int n = n1 + n2;
n1 = n2;
n2 = n;
yield return n;
}
}
long result=0;
foreach (int i in Fibonacci().TakeWhile(i => i<4000000).Where(i => i % 2 == 0))
{
result+=i;
}
Console.WriteLine(result);
The "traditional" recursive Fibonacci implementation is problematic here because it throws away all the work done along the way to the last requested term. You would have to call such a function over and over in a loop, which would duplicate a lot of work, or you could start with that implementation and add an argument to the recursive function to build up the desired sum result as the final fibonacci term is calculated. I like this much better, because it's still a general purpose fibonacci sequence at the core, rather than one you had to re-write or specialize.
Another approach is to use events (delegates) in a traditional implementation to call a separate method as each term is completed, but as I still like the iterator method better I'll leave the delegate option as an exercise for the reader.
Your problem is not that your code contains a bug; your problem is that your code contains a bug and you don't know how to find it. Solve the second problem first, and then you won't need to ask us when you have a bug, you'll be able to find it yourself.
Learning how to find bugs is hard and takes a lot of practice. Here's how I would approach this problem.
I'd start by simplifying the problem down to something I could do myself. Instead of "what's the sum of the even fib numbers that do not exceed four million?" I'd ask "what's the sum of the even fib numbers that do not exceed 40?" That's easy to work out by hand -- 2 + 8 + 34 = 44.
Now run your program in a debugger, stepping through each line, and see where things go wrong. Does your program actually add up 2, 8 and 34? And if so, does it get the correct result?
int sum = 2;
for(int f1 = 1, f2 = 2, f3 = 0; !((f3 = (f1 + f2)) > 4000000); f1 = f2, f2 = f3)
sum += f3 * (~f3 & 1);
I think the question is written to say that you would add all the even numbers together while the numbers in the sequence don't exceed four million, meaning you would add 3,999,992.
You're checking both a and b on every iteration. So that means you're double counting almost everything.
Edit:
Ok, I see your update. This is pretty basic debugging, and you should really learn to try it yourself. Think about what the values of a and b are when your loop condition stops being true.
Joel, I wrote a very some similiar code; I'm posting it anyways:
static IEnumerable<int> Fibonacci(int maximum)
{
int auxiliar = 0;
int previous = 0;
int current = 1;
while (current < maximum)
{
auxiliar = previous;
previous = current;
current = auxiliar + current;
yield return current;
}
}
Console.WriteLine(Fibonacci(4000000).Where(number => number % 2 == 0).Sum());
The trickier way:
//1: Allow declaring of recursive functions
private delegate Func<T, R> FuncRec<T, R>(FuncRec<T, R> f);
static Func<T, R> RecFunction<T, R>(Func<Func<T, R>, Func<T, R>> f)
{
FuncRec<T, R> funcRec = r => t => f(r(r))(t);
return funcRec(funcRec);
}
//Define the factorial function
public static readonly Func<ulong, ulong> Fibonacci
= RecFunction<UInt64, UInt64>(fib => n =>
(n == 1 || n == 0)
? n
: fib(n - 1) + fib(n - 2));
//Make a "continous" version
static IEnumerable<ulong> ContinousFibonacci()
{
ulong count = 0;
while(true)
{
ulong n = Fibonacci(count);
count++;
yield return n;
}
}
//Linq result
static void Main(string[] args)
{
ulong result = ContinousFibonacci()
.TakeWhile(r => r < 4000000)
.Where(IsEven)
.Aggregate<ulong, ulong>(0,(current, s) => (s + current));
Console.WriteLine(result);
Console.ReadLine();
}
///The Functional-Style method of allowing one to create recursive functions such as above was made by Bart De Smet. See http://bartdesmet.net/blogs/bart/archive/2009/11/08/jumping-the-trampoline-in-c-stack-friendly-recursion.aspx
Here's a nice way to find Fibonnaci numbers.
IEnumerable<BigInteger> Fibs()
{
for(BigInteger a = 0,b = 1;;b = a + (a = b))
yield return b;
}
// count(user input) of Fibonacci numbers
int[] array = new int[20];
array[0] = 0;
array[1] = 1;
Console.WriteLine(array[0] + "\n" + array[1]);
for (int i = 2; i < 20; i++)
{
array[i] = array[i - 1] + array[i - 2];
Console.WriteLine(array[i]);
}