0

A C#'s little problem

Hello everyone, I need your help for a little problem with my program. this is the code: " int x = 10; Console.WriteLine("the starting number is : " + x); x++; Console.WriteLine("the starting number '" + x + "' + 1: " + x); int x7 = x; x7--; Console.WriteLine("the starting number '" + x + "' - 1: " + x7); " The problem is that on output, this is the result: " the starting number is: 10 the starting number '11' + 1: 11 the starting number '11' - 1, fa: 10 " if i create a variable where copy the x's value, the program works, if i don't do it, it not works. I know why it happens, but i want ask you how i can solve it without use a new variable for do "x++" or "x--". I want use a "still" variable that can't modify the value, and use operator on it for my output.. I need to do, for example, "x = x+5" only for my output, but the x's value need still the same of the start code. PS: Sorry for that, i'm noobie :D and also, sorry for my bad english, i hope that it was understandable :( Thanks from Italy :)

26th Aug 2022, 9:41 AM
Oxerain
Oxerain - avatar
3 Answers
+ 2
You can declare constants, which can never be changed, using the const keyword. In you printout, you can print the result of expressions that use a variable or constant, but don't change it. Like: Console.WriteLine(x + 1); x++ is tricky because it also changes the value of the original variable. You cannot use it with const! There is also a technique called string interpolation, which lets you combine text and variables or expressions into a single string. Try this: const int x = 10; Console.WriteLine(
quot;The number is {x}"); Console.WriteLine(
quot;One less: {x-1}"); Console.WriteLine(
quot;Twice: {x*2}"); Console.WriteLine(
quot;The number is {x}");
26th Aug 2022, 10:04 AM
Tibor Santa
Tibor Santa - avatar
+ 2
// Try it Console.WriteLine(
quot;the starting number {x} + 1: {++x}"); Console.WriteLine(
quot;the starting number {x} - 1: {--x}");
26th Aug 2022, 9:54 AM
SoloProg
SoloProg - avatar
+ 2
Thank you!
26th Aug 2022, 10:06 AM
Oxerain
Oxerain - avatar