【问题标题】:Why my C# Code isn't Printing the Required Output为什么我的 C# 代码没有打印所需的输出
【发布时间】:2021-03-05 02:06:50
【问题描述】:

我试图创建一个程序,该程序使用多种方法来打印出基数、指数及其结果解决方案。我正在尝试让它运行,它几乎完成了,但我遇到了几个问题。代码本身似乎可以运行,但似乎没有在 Visual Studio 上打印出来。我确实在在线编译器上运行它并将其作为输出:

我的代码中似乎遗漏了一些东西,但我不清楚我可能遗漏了什么。这是我为项目创建的代码:

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

namespace Project
{
    class Program
    {
        static void Main(string[] args)
        {
            //Our initialized variables.
            int intMinBase = 1;
            int intMaxBase = 100;

            int intMinExpo = 1;
            int intMaxExpo = 10;

            //Our arrays for the project, all at a length of 5.
            long[] baseNumbers = new long[5];
            long[] exponents = new long[5];
            long[] results = new long[5];

            //Randomize the baseNumbers and exponents!
            Random randInt = new Random();
            for (long i = 0; i < 5; i++)
            {
                baseNumbers[i] = randInt.Next(intMinBase, intMaxBase);
                exponents[i] = randInt.Next(intMinExpo, intMaxExpo);
            }

            PrintArrays(baseNumbers, exponents, results);
        }

        //This is potentially experimental code for the Power Method.
        public static int Power(int baseNum, int exponent)
        {
            int answer;

            if (exponent == 1)
            {
                answer = 1;
            }
            else
            {
                answer = baseNum * Power(baseNum, exponent - 1);
            }

            return answer;
        }


        //The new method to be printed. Is this the correct manner to display this?
        public static void PrintArrays(long[] baseNum, long[] exponent, long[] result)
        {

            Console.WriteLine($"Base\tExponent\tResult");

            for (int print = 0; print < result.GetUpperBound(0); print++)
            {

                Console.WriteLine(baseNum[print]+"\t"+exponent[print]+"\t"+result[print]);

            }

        }
    }
}

我的问题主要是我遗漏了什么,为什么它似乎没有在 Visual Studio 中打印,但它却出现在在线编译器上?我怀疑问题第一部分的答案与我使用的方法有关,但我不确定。

【问题讨论】:

  • 你永远不会调用你的“实验性”Power 函数。这就是结果全为零的原因。
  • " 我确实在在线编译器上运行了它,并将其作为输出:" 好的,这个输出有什么问题?它与您期望的输出有何不同?
  • @DStanley 啊,这是有道理的。我们刚刚开始创建方法,我不确定它有什么问题。
  • @KarlKnechtel 因为结果是零。

标签: c# arrays methods exponent


【解决方案1】:

第一个错误:Power 调用的方法无处可寻,数组结果无处填充。

解决方案示例:

for (long i = 0; i < 5; i++)
{
    baseNumbers[i] = randInt.Next(intMinBase, intMaxBase);
    exponents[i] = randInt.Next(intMinExpo, intMaxExpo);
    results[i] = Power(baseNumbers[i], exponents[i]);
}

【讨论】:

  • 虽然程序似乎说我不能将“long”转换为“int”,但它肯定会到达那里。我绝对有道理,但我忘了叫它。我以为我已经完成了那里,但似乎并非如此。有转换功能,但似乎没有像我希望的那样工作。
猜你喜欢
  • 2021-12-24
  • 2022-08-18
  • 1970-01-01
  • 2021-06-21
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多