代码之家  ›  专栏  ›  技术社区  ›  Antonio

不能显示所有十进制数C#

  •  1
  • Antonio  · 技术社区  · 6 年前

    我有一个C语言的小方法来解决这个问题 基本方程 以下内容:

    Base equation

    我在付出 n个 手动值

    我们要把它吃了 X 价值是 n个 价值是 1个 .如果我对方程进行求值,得到的结果是:

    enter image description here 我的问题是输出是0, 我也试着分析结果 ,但仍然是0。

    真正的结果是 0.8888888个 但在程序输出中 .

    以下是我的代码:

    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);
            }
        }
    }
    

    我不知道我做错了什么,错过了什么,我会感激任何帮助。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Dmytro    6 年前

    只需将变量的数据类型更改为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);
    

    这就行了。

    请看这里: Implicitly converting int to double 用于C代码中的隐式转换精度。