【问题标题】:Return variable doesnt exist in context C#返回变量在上下文 C# 中不存在
【发布时间】:2015-02-22 23:39:55
【问题描述】:

抱歉,如果这是一个基本问题,我对这种东西很陌生 我有以下代码,在方法 Kep 中,我需要以递归方式计算 50 次内部的操作,然后在 50 次迭代后返回值并打印它。 当我尝试运行它时,它说该变量在上下文中不存在。 任何建议都非常感谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kepler
{
    class Kepler
    {
        static void Main(string[] args)
        {
            //Variables
            double M = 0; //Anomalia
            double e = 0; //Excentricidad
            double e0 = 0; //Excentricidad Corregida
            //double E1=0; 
            double E0 = 0; //


            Console.WriteLine("Ingresa M:");
            string m = Console.ReadLine();
            M = Convert.ToDouble(m);

            Console.WriteLine("Ingresa e:");
            string ee = Console.ReadLine();
            e = Convert.ToDouble(ee);

            //Calculo de e0
            e0 = e * 180 / Math.PI;

            Console.WriteLine("Ingresa E0:");
            string EE0 = Console.ReadLine();
            E0 = Convert.ToDouble(EE0);

            //calculo de las funciones trigonometricas
            double sin = Math.Sin((E0 * Math.PI / 180));
            double cos = Math.Cos((E0 * Math.PI / 180));
            int cuenta = 0;

            Console.Clear();
            double total = Kep(M, e, sin, cos, e0, E0, ref cuenta);
            Console.WriteLine("Total=" + total);
            Console.ReadLine();
        }

        static double Kep(double M, double e, double sin, double cos, double e0, double E0, ref int cuenta)
        {
            double E1 = 0;
            for (cuenta = 0; cuenta <= 50; cuenta++)
            {
                E1 = E0 + ((M + e0 * sin - E0) / (1 - e * cos));
                Console.WriteLine("E1 hasta ahora" + E1);
            }
            return Kep(M, e, sin, cos, e0, E1, ref cuenta);
        }
    }
}

【问题讨论】:

  • 这可能会在您运行时崩溃,因为您递归调用相同的函数而没有任何停止它
  • 谢谢大家,成功了:)

标签: c# variables recursion return


【解决方案1】:

for 循环之前声明您的变量double E1,然后在循环内分配它。确保初始化变量以使编译器满意。什么值无关紧要,因为它将在第一次迭代中被覆盖。

另外,请注意您的 for 循环执行 51 次,而不是 50 次。如果您希望它执行 50 次,请将 for 循环中的 &lt;= 更改为仅 &lt;

此外,正如 Lior Raz 所指出的(很好),您需要在 Kep 函数中添加停止条件,因为递归调用将永远继续,最终导致堆栈溢出。

【讨论】:

  • 谢谢,我试过了,但现在显示错误 1 ​​Use of unassigned local variable 'E1'
  • 给它一个初始值让编译器满意。 double E1 = 0; 应该这样做。
  • 如果我这样做,E1 将每次重置为 0(我认为),我需要知道每次迭代的值
  • E1 只有在没有东西循环时才会为空
【解决方案2】:

将变量E1移到循环外,即放在循环之前

问题是它与 return 语句不在同一个上下文中,它不知道它存在

// initialize E1 in the case cuenta is greater than or equal to 50
double E1 = 0;
for (cuenta=0; cuenta <= 50; cuenta++)
    {
        E1 = E0 + ((M + e0 * sin - E0) / (1 - e * cos));
        Console.WriteLine("E1 hasta ahora" + E1);
    }

【讨论】:

  • 谢谢,我试过了,但现在显示错误 1 ​​Use of unassigned local variable 'E1'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 2014-05-10
  • 2013-06-30
相关资源
最近更新 更多