You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#自定义Fraction类调用Multiply方法仅第二个参数生效问题求助

问题根源

你代码的核心问题出在成员的static修饰符使用错误:

  • 存储分子分母的fraction数组被声明为static静态成员,静态成员属于类本身而非单个实例,所有Fraction类的实例共享同一份数组存储空间
  • 你先后创建frac2(30/40)、frac1(100/200)两个实例时,后创建的实例写入的分子分母会直接覆盖前一个实例的写入值,最终所有实例读取到的都是最后一次赋值的100/200
  • 额外的逻辑错误:GetFraction方法完全没有用到传入的Fraction实例参数,不管传什么实例,返回的都是当前类的静态数组,所以才会出现两个入参读取到的数值完全相同的问题

修复方案

调整后的Fraction类代码

using System;

namespace Math
{
    class Fraction
    {
        // 改为实例成员,每个Fraction实例单独存储自己的分子分母
        private readonly int[] _fraction = new int[2];
        public Fraction(int numer, int denom)
        {
            Console.WriteLine($"Numerator & Denominator: {numer}/{denom}\n");
            _fraction[0] = numer;
            _fraction[1] = denom;
        }

        // 改为实例方法,直接返回当前实例的分子
        public int GetNumer()
        {
            return _fraction[0];
        }

        // 改为实例方法,直接返回当前实例的分母
        public int GetDenom()
        {
            return _fraction[1];
        }

        // 实例乘法方法:当前实例和传入的另一个分数实例相乘
        public Fraction Multiply(Fraction other)
        {
            int resNumer = this.GetNumer() * other.GetNumer();
            int resDenom = this.GetDenom() * other.GetDenom();
            return new Fraction(resNumer, resDenom);
        }

        // 实例打印方法,直接输出当前实例的分数值
        public void Print()
        {
            Console.WriteLine($"{GetNumer()}/{GetDenom()}");
        }
    }
}

调整后的测试代码

using System;

namespace Math
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Math");
            Console.WriteLine("----");

            Fraction frac1 = new Fraction(30, 40);
            Fraction frac2 = new Fraction(100, 200);
            // 计算frac1 * frac2
            Fraction result = frac1.Multiply(frac2);
            result.Print();
            // 输出结果为3000/8000,可自行添加最大公约数计算逻辑实现约分
        }
    }
}

内容的提问来源于stack exchange,提问作者user16850055

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:57:02