-1

I am trying to utilize the Math.Cos() function in c# to print a range of of values from 0 to 2pi increasing by .1pi, so 20 iterations. The problem is I cannot get my x value to change as the for loop is executing.

    public void Cos()
    {
        double x = 0;
        double a = Math.PI * x;
        double b = Math.Cos(a);

        for (int i = 0; i < 21; i++)
        {

            Console.WriteLine("Cos({0})pi = {1}", x, b);
            x += .1;

        }
    }

When I print the results to the console, it only remembers the value of cos at x = 0. So I just get 1, 20 times as a result for Cos(.1)pi, Cos(.2)pi, etc...

pijoborde
  • 29
  • 7
  • 1
    `it only remembers the value of cos at x = 0` Because you never calculate it again after the initialization of `b`. – tkausl Jan 31 '19 at 01:27
  • 1
    Put the definitions of `a` and `b` inside the loop. They need to be recalculated for each new value of `x`. – Blorgbeard Jan 31 '19 at 01:27
  • 3
    More generally, "double b = Math.Cos(a);" does not mean "when I ask what `b` is, calculate cosine of `a`", it means "calculate the cosine of `a` *now*, and when I ask what `b` is, tell me the number you calculated". – Blorgbeard Jan 31 '19 at 01:29
  • Read every statement with the word "immediately" before it. So "double x = a + b + c" means "immediately store into variable x of type double the value of a + b + c". Evidently, you're doing that up top, but never again after the x += .1 line where you "immediately add to x the value 0.1". You have to recalculate a and b before they'll have the value you want. – Warty Jan 31 '19 at 01:30
  • I see what you are saying. Thank you. – pijoborde Jan 31 '19 at 01:36
  • Doesn't your loop produce 21 iterations? – ProgrammingLlama Jan 31 '19 at 01:47
  • Yes John, technically so since 0 and 20 are included. – pijoborde Jan 31 '19 at 01:48
  • Have you stepped through the loop in the debugger and examined `x`, `Math.Cos(x)` and `b`? – HABO Jan 31 '19 at 02:57

1 Answers1

4

I am trying to utilize the Math.Cos() function in c# to print a range of of values from 0 to 2PI increasing by .1PI

This sounds like a job for a for loop, where we start with a value of 0, and increment by .1 * PI on each iteration until it reaches 2 * PI.

Since a for loop has an initializer part, a condition part, and an incrementing part, it is the perfect construct. No need for an extra variable that increments from 0 to 20 - we can use the for loop to do our incrementing of x and our testing the exit condition!

public static void Cos()
{
    for (double x = 0; x <= Math.PI * 2; x += Math.PI * .1)
    {
        Console.WriteLine("Cos({0})PI = {1}", x, Math.Cos(x));
    }
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43