If I have a program where x = 2 and I subtracted x by 1, making x = 1. Is there any way to make it so that whenever x will be printed in the program, it will print 1?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x-1);
Console.WriteLine(x); //make x's new value 1
}
}
}
you need to store the calculation to the variable
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x);//will print 2
x = x-1; //applying calculation and storing to same variable
Console.WriteLine(x); //make x's new value 1 : Done
}
}
}
You are Displaying the Correct answer.
2 - 1 will Display 1. But u arent changing the Variable or even touching it. You are just using it for a Reference to Calculate what is x - 1?
Displaying only X now will Display 2 as it has NOT been changed.
Setting (Changing the Value of a Variable) is not (normaly) possible inside a Function. There are Functions which take ref params. Which will work with its memory.
You simply need a one-liner.
x = x - 1 translated the value of x is set to the value of x - 1.
it seems much for a simple calculation to require a whole line as it is. But programming will always be one of these things where u have to think literall
This whole problem is a great example for Rubberducking.
think about it literall... line for line what exactly happens and why should it not work?
Write
x--;
Console.WriteLine(x);
That's how you change the value of a variable - you have to assign it a new value.
Alternatively you can write x = x - 1; longhand instead of using the decrement (--) operator.
What you did in your version was to create some output which was the result of x-1, but that doesn't change the original value of x, it just uses x in another calculation.
Related
Given int x, I want to be able to check if it has increased or decreased by 2. Is there a clean way to do this using the +- condition or should I check both if increased and if decreased separately using or?
Is it possible to make the if statement shorter or do I just have to check multiple conditions at once instead of both at the same time using C#
You can check it using || operator, something like this, here prevX is previous value.
if (x - prevX == 2 || prevX - x == 2) {
}
I would do this by storing initial value of variable and then comparing it with actual using Math.Abs method
var initialX = x; // store value of x before modification
// operations on x
if (Math.Abs(initialX - x) == 2)
{
// x was decreased or increased by 2
}
As long as x is value type, it would be convenient to wrap up operations in separate method and use it like this:
if (Math.Abs(PerformOperations(x) - x) == 2)
{
// x was decreased or increased by 2
}
But PerformOperations can't take params as reference (with ref keyword).
public record Cube(int x, int y, int z, int w);
I recently ran across a time I was doing this:
var next = new Cube(existing.x + 1, existing.y, existing.z, existing.w);
and I thought there must be a cleaner way to add arbitrary values to the record. But when I try this:
var next = existing with { x = x+1 };
It cries because you do not have access to the values to add to. Instead I have to do this:
var next = existing with { x = existing.x+1 };
Am I just wanting too much from the with keyword?
My understanding of with syntax is exactly that - you must reference the name of the object to the left of the width statement. This seems to line up with the spec here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/records
While the x = x + 1 is convenient, it is not very expressive on the source of where x is coming from.
The x in x = x+1 is the x of the next instance to be created. However, this instance does not yet exist at that point that's why the compiler complains. Instead, you have to state explicitly that the second x is the one of the existing instance.
So I'm a complete newb to unity and c# and I'm trying to make my first mobile incremental game. I know how to format a variable from (e.g.) 1000 >>> 1k however I have several variables that can go up to decillion+ so I imagine having to check every variable's value seperately up to decillion+ will be quite inefficient. Being a newb I'm not sure how to go about it, maybe a for loop or something?
EDIT: I'm checking if x is greater than a certain value. For example if it's greater than 1,000, display 1k. If it's greater than 1,000,000, display 1m...etc etc
This is my current code for checking if x is greater than 1000 however I don't think copy pasting this against other values would be very efficient;
if (totalCash > 1000)
{
totalCashk = totalCash / 1000;
totalCashTxt.text = "$" + totalCashk.ToString("F1") + "k";
}
So, I agree that copying code is not efficient. That's why people invented functions!
How about simply wrapping your formatting into function, eg. named prettyCurrency?
So you can simply write:
totalCashTxt.text = prettyCurrency(totalCashk);
Also, instead of writing ton of ifs you can handle this case with logarithm with base of 10 to determine number of digits. Example in pure C# below:
using System.IO;
using System;
class Program
{
// Very simple example, gonna throw exception for numbers bigger than 10^12
static readonly string[] suffixes = {"", "k", "M", "G"};
static string prettyCurrency(long cash, string prefix="$")
{
int k;
if(cash == 0)
k = 0; // log10 of 0 is not valid
else
k = (int)(Math.Log10(cash) / 3); // get number of digits and divide by 3
var dividor = Math.Pow(10,k*3); // actual number we print
var text = prefix + (cash/dividor).ToString("F1") + suffixes[k];
return text;
}
static void Main()
{
Console.WriteLine(prettyCurrency(0));
Console.WriteLine(prettyCurrency(333));
Console.WriteLine(prettyCurrency(3145));
Console.WriteLine(prettyCurrency(314512455));
Console.WriteLine(prettyCurrency(31451242545));
}
}
OUTPUT:
$0.0
$333.0
$3.1k
$314.5M
$31.5G
Also, you might think about introducing a new type, which implements this function as its ToString() overload.
EDIT:
I forgot about 0 in input, now it is fixed. And indeed, as #Draco18s said in his comment nor int nor long will handle really big numbers, so you can either use external library like BigInteger or switch to double which will lose his precision when numbers becomes bigger and bigger. (e.g. 1000000000000000.0 + 1 might be equal to 1000000000000000.0). If you choose the latter you should change my function to handle numbers in range (0.0,1.0), for which log10 is negative.
I'm still learning the ropes with C# programming. I am trying to write an application to solve Knight's Tour but have run into some grief when trying to get possible future positions for the knight.
For positions I am using a very simple struct:
public struct Position
{
public enum BoardRank { A = 1, B, C, D, E, F, G, H };
public BoardRank X;
public int Y;
}
In the knight class, my PossibleMoves() method begins like this:
public List<Position> PossibleMoves(Position position)
{
List<Position> positions = new List<Position>();
int[] multiply = new int[]{1, -1};
foreach (int times in multiply)
{
try{
Position possible = new Position();
possible.X = position.X + (Behaviour.X * times);
possible.Y = position.Y + (Behaviour.Y * times);
positions.Add(possible);
}
...
For position = A1 and times = -1, you can see how Behaviour.X could quickly fall out of bounds, but I assumed this would have been picked up by the try block.
I tried adding a {get; set;} on the enum declaration but that threw some useless syntax errors in VS2010.
Is there anything else I can try here to stop my enum from going out of bounds?
I assumed this would have been picked up by the try block.
Nope. Enums in C# are "named numbers" effectively. They're not a complete set of values for the type.
Is there anything else I can try here to stop my enum from going out of bounds?
You can use Enum.IsDefined to check whether a value exists in the original enum. I would personally stop using public fields, and instead make Position immutable - then validate the value in the constructor. You could also have methods such as WithX which returned a new value based on the current value with just X changing. While you've got public fields, you're never going to be able to trust that any particular value is valid though.
It may be useful to use modulo to keep the values within a specific range:
possible.X = (position.X + (Behaviour.X * times)) % ((int)BoardRank.H + 1);
This way I am not sure whether an enum is the best solution here, as we're working with integers anyway. The numbers must be a sequence with no gaps and you have to make sure you take the highest defined enum value plus one. Thus, if you add a I to your enum, you need to change the modul.
Here I have a very simple program to illustrate how it works:
enum Foo { A, B, C }
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i % ((int)Foo.C + 1));
}
}
As you see we take i modulo C + 1 which makes C's integer value the actual range maximum. This is the output:
0, 1, 2, 0, 1, 2, 0, 1, 2, 0
I have the following method:
static Random rr = new Random();
static void DoAction(Action a)
{
ThreadPool.QueueUserWorkItem(par =>
{
Thread.Sleep(rr.Next(200));
a.Invoke();
});
}
now I call this in a for loop like this:
for (int i = 0; i < 10; i++)
{
var x = i;
DoAction(() =>
{
Console.WriteLine(i); // scenario 1
//Console.WriteLine(x); // scenario 2
});
}
in scenario 1 the output is: 10 10 10 10 ... 10
in scenario 2 the output is: 2 6 5 8 4 ... 0 (random permutation of 0 to 9)
How do you explain this? Is c# not supposed to preserve variables (here i) for the anonymous delegate call?
The problem here is that there is one i variable and ten instances / copies of x. Each lambda gets a reference to the single variable i and one of the instances of x. Every x is only written to once and hence each lambda sees the one value which was written to the value it references.
The variable i is written to until it reaches 10. None of the lambdas run until the loop completes so they all see the final value of i which is 10
I find this example is a bit clearer if you rewrite it as follows
int i = 0; // Single i for every iteration of the loop
while (i < 10) {
int x = i; // New x for every iteration of the loop
DoAction(() => {
Console.WriteLine(i);
Console.WriteLine(x);
});
i++;
};
DoAction spawns the thread, and returns right away. By the time the thread awakens from its random sleep, the loop will be finished, and the value of i will have advanced all the way to 10. The value of x, on the other hand, is captured and frozen before the call, so you will get all values from 0 to 9 in a random order, depending on how long each thread gets to sleep based on your random number generator.
I think you'll get the same result with java or any Object oriented Language (not sure but here it seems logical).
The scope of i is for the whole loop and the scope of x is for each occurrence.
Resharper helps you top spot this kind of problem.