Why my integer number assignment is invalid? - c#

This is my test code,it's very simple:
class Program
{
static void Main(string[] args)
{
int number = 0;
int newNumber = number++;
Console.WriteLine("the old number is {0},the new number is:{1}", number, newNumber);
Console.Read();
}
}
whereas the output result is:'the old number is 1,the new number is:0',I think it's opposite with the result I want.

using the postfix increment ++ operator, it first returns the original value, then increments. To get what you want use the prefix increment operator like
int newNumber = ++number;
But if you don't want to change number, don't use an incrementing operator, use addition/subtraction instead.

That is because number++ updates the value of number by incrementing it (PostFix). This is done after using the original value in the expression it is used. To achieve the desired behaviour, You can use:
int number = 0;
int newNumber = number + 1;

Here, you have used number++ which is Post increment operator.
It assigns the value first and then increments its value.
You can achieve your desired output in two ways :
Use Pre increment operator
int newNumber = ++number;
Simply adding 1 to number variable and then assigning it to newNumber
int newNumber = number + 1;

Related

Print message every 5

Modifying a plugin for a Rust game server, and I'm not too great at C#. I currently have the system set up to print the votes to chat every time a new vote comes in, but want it based on percentage or every 5 votes. How would I do that? This is my current code.
public int tallyVotes() {
int yesVotes = 0;
foreach (var votes in votesReceived) {
if (votes.Value)
yesVotes = yesVotes + 1;
}
return yesVotes;
couldn't you return yesVotes/5 as an integer, essentially giving you 1 vote for every 5.
int voteWeighting = 5;
return (int)yesVotes/voteWeighting;
if you're looking for when to print it then the generic fizz buzz solution would fix it.
int printWeighting = 5;
if (yesVotes%printWeighting ==0)
{
//print stuff here
}
this works by using the modulus function "a%b" it will return the remainder when you divide a by b and as such return a number less than "b" but greater or equal to zero. as such if you only ever increment by 1 the number, then when a mod b is 0 you have incremented b times.
Fizzbuzz example

simple procedural maths program in C#

so I am creating a very simple program in C# (my first one).
It should do an average of X numbers.. instead of writing it all out manually, it'll be much better done procedurally (I'm not sure if that's even a word). Basically as I've done with the 'amount' in the example below. I could just divide it by 2 (in this case). But instead I have a variable that increases with each new entry - so the program would work regardless of how many entries there are.
The same thing I'd need to do with the variables 'first', 'second' etc. I need some variable that would change dynamically, based on the number of entries. This should be a peace of cake algorithm-wise but this is my first day with C# and I can't manage to do it (namely because I am lacking the knowledge of syntax).
double first;
double second;
int amount = 0;
double result;
Console.Write("Write your first number");
first = int.Parse(Console.ReadLine());
++amount;
Console.Write("Write your second number");
second = int.Parse(Console.ReadLine());
++amount;
result = (first + second) / amount;
Console.Write("The average of your numbers is: " + result);
Thanks
Here's the gist of what I think you want. I'll use pseudocode to give you the opportunity to learn the C#:
create a list of numbers
output prompt
read input line
while the input line had a value
parse the input value
add the parsed value to the list of numbers
output prompt
read input line
calculate the sum of the values divided by the length of the list
output the calculated average
I think you're after the recusive average?
class Program
{
static void Main(string[] args)
{
//Compute Average Recursively:
int average_count = 0;
double average = 0;
average = RecursiveAverage(average, ref average_count, 1);
average = RecursiveAverage(average, ref average_count, 2);
average = RecursiveAverage(average, ref average_count, 3);
average = RecursiveAverage(average, ref average_count, 4);
Console.WriteLine(average); //2.5
}
private static double RecursiveAverage(double previous, ref int average_count, double next)
{
average_count += 1;
return ((average_count - 1.0) / (average_count)) * previous + (1.0 / (average_count)) * next;
}
}
See: http://people.revoledu.com/kardi/tutorial/RecursiveStatistic/Time-Average.htm
Update: Keep updating the average indefinitely (or until average_count gets too large to store without a BigInteger ) without having to remember all the numbers...
while (true)
{
var next = int.Parse(Console.ReadLine());
average = RecursiveAverage(average, ref average_count, next);
Console.WriteLine("Average is now: " + average);
}

Increase an int by one

On another page I've said that nr = 0
var number = this.NavigationContext.QueryString["nr"];
int Nr = Convert.ToInt16(number);
And this works, Nr = 0
Now I want to upgrade Nr by one:
int next = Nr++;
Unfortunately this doesn't work... next = 0 too, but it supposed to be 1.
Could someone explain to me what I'm doing wrong?
Nr++ increments and returns the original value of Nr.
++Nr increments and returns the new value of Nr. So what you want is:
int next = ++Nr;
In C# (or C++), the statement
int next = Nr++;
translates to, "assign the value of Nr to variable next, and then increment Nr by 1.
If you want Nr to increment first, your statement should look like this:
int next = ++Nr;
Here is the definition of the ++ operator: http://msdn.microsoft.com/en-us/library/36x43w8w.aspx
the problem is ...Nr is incremented after Nr set to next use next=Nr+1;
There are two increment operators - pre-increment ++c and post-increment c++.
var x = ++c; is equivalent to
c = c + 1;
var x = c;
while var x = c++; is equivalent to
var x = c;
c = c + 1;
and therefore x either receives the value before or after c got incremented.

MVC - Controller - Make a Simple Math Calculation - Variable + 1

I have a little problem to make a simple math calculation in the controller.
what I try to do is add +1 to a number of a variable.
Here is an example for you to understand better what I try to do:
var a= formcollection["Id_this"];
var next = a + 1;
Note: the value of "Id_this" is "1".
The result I need for the variable next is 2
My problem is that the result of the variable next is "12".
a is a string. Adding a number to a string results in the number being converted to a string and being concatenated.
To make it work, you first need to convert a to a number:
var next = Convert.ToInt32(a) + 1;
Reason is you are doing string concatenation. Try this safe approach:
int number;
int next = 0;
if(Int32.TryParse(formcollection["Id_this"], out number))
{
next = number + 1;
}
else
{
//formcollection["Id_this"] is not a number
}
like this :
var next = int.Parse(a) + 1;

Why is this Loop Working Infinitely

This is a simple while loop in C# but it is working infinitely.
int count = 1;
while (count < 10)
{
count = count++;
}
Why is this so?
The expression count++ returns the original value of count, then increments the value afterwards.
So you are overwriting count with the same value every time. Just do this:
count++;
For the curious, here's a link to Eric Lippert's article which distinguishes between operator precedence and the order of evaluation -- it's an interesting read:
http://blogs.msdn.com/b/ericlippert/archive/2009/08/10/precedence-vs-order-redux.aspx
This will loop infinitely.
There are two types of incrementing a variable:
Here count++ and ++count both are different if you have used ++count it will work.
Here count = count++ means count variable will be incremented by one then assigns the earlier value 1 to the count variable itself so count remains unchanged.
count = count++; does not increment count by one. x++ is the post increment operator, which means that the value returned by the expression is the old value. Thus, in your code, the following happens:
int oldValue = count;
count = count + 1;
count = oldValue;
What you probably meant to write was count++; (without the "count =").
More details about this can be found in the following SO question:
What does "count++" return in C#?
The ++ operator first saves the current value then increments and finally returns the saved value, so count will never change.
Eiter use the ++ operator or do an assignment. These are all equivalent:
count++;
count += 1;
count = count + 1;
count = count++;
This is a post-increment. It does the following.
int temp = count;
count++;
count = temp;
So you're not incrementing count. Use the following instead:
while (count < 10)
{
++count;
}
because
count++
returns count, not count + 1
just have count++ with no assignment or:
count = ++count;
the last one only to explain but you should not use it...
from: ++ Operator (C# Reference)
The first form is a prefix increment operation. The result of the
operation is the value of the operand after it has been incremented.
The second form is a postfix increment operation. The result of the
operation is the value of the operand before it has been incremented.
Numeric and enumeration types have predefined increment operators.
User-defined types can overload the ++ operator. Operations on
integral types are generally allowed on enumeration.
It is infinite because you aren't actually incrementing count.
count = count++; assigns the value of 1 to count and then increments count but since you don't assign the incremented value count never increases.
You need to do either:
count++;
or
count = ++count;
Let me ask you a question why do you make two operations on a single variable while one is enough?
what was your intention? count++ itself was enough so why again assign to count. May be you want to do something else.
You could have only count++, or ++count or count+1. I think other ways causes two operations.
Sorry for my way of writing.

Categories

Resources