Why do the following codes return 1,1,1 instead of 1,2,3? I'd like to keep the int tempvalue so that I can use it somewhere else. And It works if I call Console.WriteLine(count()) directly.
class Program
{
private static int start = 0;
static void Main(string[] args)
{
int temp = count();
Console.WriteLine(temp);
temp = count();
Console.WriteLine(temp);
temp = count();
Console.WriteLine(temp);
}
static int count()
{
return start + 1;
}
}
If you expect the count to return a value that increments at each call, you should store the modified value back in the variable :
static int count()
{
start = start + 1;
return start;
}
Ndech's code will perform the desired output from your (modified) question, the reason you're seeing 1,1,1 each time is due to:
static int count()
{
return start + 1;
}
When start = 0, if you return start + 1 each time you call count(), then each time it's going to be 0+1. the code example provided by Ndech will do:
start = 0; // before first console.write
count();
start = 1; // first console.write
count();
start = 2;
etc...
another way this could be written is:
static int count()
{
return ++start; // take the current value of start, and add one to it.
}
Related
So this is the Program cs. I want to change the value of int in my StaticClass.cs ** I want to delcare a printing sentence " How long do you want me to generate " then change the value of N in StaticClass.
class Program
{
static void Main(string[] args)
{
Constructor ct = new Constructor(StaticClass.n);
//ct.xmethod(StaticClass.n);
Console.ReadKey();
}
}
Here my constructor class. Method of Pascal Triangle
class Constructor
{
int[][] triangle = new int[StaticClass.n][];
public Constructor(int n)
{
xmethod(n);
}
public void xmethod(int n)
{
for (int row = 0; row < triangle.Length; row++)
{
//Each row is a subarray of length 1 greater than row number
triangle[row] = new int[row + 1];
//set the values in a row
for (int k = 0; k < triangle[row].Length; k++)
{
// if not first or last element in the row
if (k > 0 & k < triangle[row].Length - 1)
//set it to sum of the element above it
//and the one above and to the left
triangle[row][k] = triangle[row - 1][k - 1] + triangle[row - 1][k];
//otherwise this is an end point, set it to 1
else
triangle[row][k] = 1;
//display value
Console.Write(triangle[row][k] + "\t");
}
// Finished processing row-send cursor to next line
Console.WriteLine();
}
}
}
Here my StaticClass for the long of Pascal Triangle
class StaticClass
{
public const int n = 15;
// I want to change the value of N using the Console Writeline.
}
n needs to be updatable then instead of const use static; but Console.WriteLine() is not something you would use to change the value. You'll need to be more clear about what you want to do. Do you want someone to input the value of n - with a Console.ReadLine?
So ... from what I gather -- I think you want to change your Main to write your question: " How long do you want me to generate " then read the line for user input. Then print your triangle. Something like :
static void Main(string[] args)
{
Console.WriteLine("How long do you want me to generate? ");
int inNum = int.Parse(Console.ReadLine());
Constructor ct = new Constructor(inNum);
Console.ReadKey();
}
Then from what I see ... your Constructor needs to change:
public Constructor(int n)
{
triangle = new int[n][];
xmethod(n);
}
You cannot change the value of a const. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants
Use a static property instead.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
static class StaticClass
{
public static int n = 15;
// I want to change the value of N using the Console Writeline.
}
Make your public const field a public static property instead:
public static int N { get; set; } = 15;
Change it like
StaticClass.N = 16;
You said "change it with WriteLine" - WriteLine outputs things, it doesn't change thing. Perhaps you meant ReadLine:
Console.WriteLine("How many levels? ");
string input = Console.ReadLine();
StaticClass.N = int.Parse(input);
Do please find a better name for StaticClass; classes should be named for what they represent in a more real world sense (like.. Configuration?) not what they are in a C# sense (yes, it's a static class, but it doesn't mean we should call it that)
So I'm trying to take a value from Main(), edit it with a function, then keep the changed value.
EDIT:
static void Divisors(int i, int count)
{
while (i % 2 == 0 && i != 0)
{
divisors[count] = i/2;
count++;
}
}
static void Main(string[] args)
{
int i = 10;
int count = 0;
int[] divisors = new int[1000];
Divisors(i);
return count;
}
Wanted Output: whatever it counted
Actual Output: 0
Parameters are passed by-value in C#, so you can't assign new values to them and have them affect the original arguments passed to them like that. You could instead return a value from Change, and assign it to i in the Main method:
static int Change(i)
{
return i + 2;
}
static void Main(string[] args)
{
int i = 0
i = Change(i);
}
For my application, I have built an iterator and I need to use each of the values it yields along with the previous one.
For example, consider the following iterator, that yields the first terms of the Fibonacci sequence:
public static IEnumerable<int> GetFibonacciNumbers(int count)
{
int a = 0;
int b = 1;
int i = 0;
while (i < count)
{
yield return a;
int temp = a;
a = b;
b = temp + b;
i++;
}
}
Now I want to use this enumerator to compute increasingly accurate estimates of the golden ratio, which means I need to use the yielded value along with the previous one. The following approach kind of works:
static void Main(string[] args)
{
int fib0 = 0;
foreach (int fib1 in GetFibonacciNumbers(10))
{
var phi = (double)fib1 / fib0;
Console.WriteLine(phi);
fib0 = fib1;
}
}
The issues are that the first value for phi is wrong, as the first value for fib0 used isn't actually part of the sequence.
Just return both the current and previous values from your iterator:
public static IEnumerable<(int prevValue, int currentValue)> GetFibonacciNumbers(int count)
{
int a = 0;
int b = 1;
int i = 0;
while (i < count)
{
yield return (a, b);
int temp = a;
a = b;
b = temp + b;
i++;
}
}
The above uses C# 7.0 Tuple Syntax, but you can easily convert it to use a regular Tuple<int, int> as well.
You can have the enumerating function keep track of the previous and current values and return them as a tuple. For example, in the fibonacci example it would be something like this:
static IEnumerable<(int Previous, int Current)> GetFibonacciNumbers(int count)
{
var (previous, current) = (0, 1);
for(int i = 0; i < count; i++)
{
yield return (previous, current);
(previous, current) = (current, previous + current);
}
}
Haim770's answer is correct if you want to modify your generator. However, you might also want to use a general purpose method that you can then reuse with any IEnumerable<T>:
public static IEnumerable<(T prevValue, T currentValue)> OverlappingPairs<T>(IEnumerable<T> source)
{
bool first = true;
T previous = default;
foreach (var item in source)
{
if (!first)
yield return (previous, item);
first = false;
previous = item;
}
}
(And of course, if you add this before the parameter and put it in a static class, it'll work as an extension method)
Some fibonacci sequences start with 1 and 1 instead of 0 and 1. So maybe that could solve your problem.
I have typed up some code to try and practice what I have learned in my programming course. Something is wrong with my logic as I am not getting the answer I am supposed to get.
I have searched and google and rewatched the training videos but nothing seems to help.
namespace TenPinBowling
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("Would you like to bowl, Y or N: ");
var answer = Console.ReadLine();
if (answer == "n")
{
Console.WriteLine("Thanks for playing, press any to exit :)");
Console.ReadKey();
break;
}
Score();
}
}
static void Score()
{
{
Random pins = new Random();
var pinsKnockedDown = pins.Next(0, 10);
//var totalScore = 0;
Console.WriteLine("You bowled a: " + pinsKnockedDown);
//var result = totalScore + pinsKnockedDown;
Console.WriteLine("You're total score is: " + Tally(pinsKnockedDown));
}
}
static int Tally(int score)
{
{
int result = 0;
result = result + score;
return result;
}
}
}
}
I was hoping my second method would keep a running total of my score but it resets to the individual score every time.
In
static int Tally(int score)
{
{
int result = 0;
result = result + score;
return result;
}
}
you create a new local variable result each time you invoke the method, so the record of past scores is lost. Making result a field of the class would allow it to persist for the duration of the game. A minimal code change might be:
private static int result = 0;
static int Tally(int score)
{
result = result + score;
return result;
}
I would guess you always need to keep track of your total score, if it should not reset. Right now you always add the current score to zero (in Tally). If you put int result outside of tally it should keep track accordingly.
I am using recursion to add two numbers together, By adding 1 to the first input one at a time until I have reached the value of the second.
Why does this work...
private static int AddMethod(int input1, int input2)
{
if (input2 == 0)
{
Console.WriteLine(input1);
return (input1);
}
else
{
input1++;
input2--;
return AddMethod(input1, input2);
}
}
But not this..
private static int AddMethod(int input1, int input2)
{
if (input2 == 0)
{
Console.WriteLine(input1);
return (input1);
}
else
{
return AddMethod(input1++, input2--);
}
}
I am using Visual Studio 2010 and .Net 4.0
Because return AddMethod(input1++, input2--); first passes your inputs, and THEN increments and decrements.
Try
return AddMethod(++input1, --input2);
Post fix increment works by first "assigning" the value, then incrementing the value.
Compare:
int a = 1;
int b = 1;
int x = a++;
int y = ++b;
So in your case, the value you pass to AddMethod is the unchanged value, it modifies the value of input1 and input2 after they are passed.
Because the ++ and -- operators are executed after passing the values as parameters to the function.
Your code:
return AddMethod(input1++, input2--);
Is equal to:
int result AddMethod(input1, input2);
input1++;
input2--;
return result;
Instead of all this, you could use:
return AddMethod(++input1, --input2);