为什么当前上下文中不存在“total”?

问题描述 投票:0回答:1

我试图在不使用 Math.Pow() 的情况下打印 n 的 p 次方。 这是伪代码:

从用户处获取两个整数 n , p

使用 for 循环计算幂函数 n ** p,而不使用 Math.Pow() 方法。 输出结果

使用 while 循环重复计算 输出结果

使用 do-while 循环重复计算 输出结果。

我尝试以多种方式声明变量,并在 for 循环中返回总计。

using System;


public class Powers
{
    
    public static void Main()
    {

        Console.WriteLine("Enter the base integer here:");
        int n = int.Parse(Console.ReadLine());

        Console.WriteLine("Enter exponent here:");
        int p = int.Parse(Console.ReadLine());

        for (int total = 1, counter = 1; counter <= p; ++counter)
        {
            
            total = total * n;          
        }

        Console.Write($"{n} to the {p} power is {total}");
    }
}
c# loops return iteration
1个回答
0
投票

for
子句中定义的变量仅存在于
for
循环内部。如果你希望它在循环中生存,你必须在外部定义它:

        int total = 1;
        for (int counter = 1; counter <= p; ++counter)
        {
            total = total * n;          
        }

        Console.Write($"{n} to the {p} power is {total}");
© www.soinside.com 2019 - 2024. All rights reserved.