首页 > 解决方案 > 在 C# 中使用命令行参数对数字进行阶乘

问题描述

我正在练习在线编译器。我必须编写阶乘程序,给定来自 STDIN 的数字 n,它将 n 的阶乘打印到 STDOUT:

我写了这个

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        int result=1;
        int fact = int.Parse(args[0]);
        
        if(fact==0)
        {
            Console.WriteLine(result);
        }
        else
        {
            for(int i=fact;i>=1;i--)
                result = i*result;
        }
        Console.WriteLine(result);
    }
}

我知道在 C 中,我们使用atoi. 我也尝试使用简单的 Console.ReadLine() 但它只是失败了测试用例。

目前,我收到以下错误 -

Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0 

标签: c#command-linestdoutstdin

解决方案


推荐阅读