Antonio
Antonio

Reputation: 442

Cant show all decimal numbers C#

I have a little method in C# with the purpose of solve this base equation:

Base equation

I´m giving n and x values manually

We are going to supose that X value is 3 and n value is 1. If I evaluate the equation I got this result:

enter image description here My problem is that the output is 0, I tried to parse the result as well, but still apearing 0.

The real result is 0.88888888 but in the program output I just got 0.

Here is my code:

using System;

namespace Polinomio
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 3;
            int n = 1;

            double result = 0;

            for (int i = 0; i <= n; i++) {
                result += (double)(Math.Pow((x - 1) / 3, Math.Pow(2, i))) / Math.Pow(2, i);           
            }

            Console.WriteLine(result);
        }
    }
}

I don't know what I'm doing wrong or what I´m missing, I will appretiate any help.

Upvotes: 1

Views: 112

Answers (1)

Dmytro
Dmytro

Reputation: 1600

Simply change data types of your variable to double.

 double x = 3;
 int n = 1;

 double result = 0;

 for (int i = 0; i <= n; i++)
 {
      result += (Math.Pow((x - 1) / 3, Math.Pow(2, i))) / Math.Pow(2, i);
 }

 Console.WriteLine(result);

This will do the trick.

Take a look here: Implicitly converting int to double for implicit conversion precidence in C# code.

Upvotes: 3

Related Questions