【问题标题】:Calculate the algebraic expressions in C# [duplicate]在 C# 中计算代数表达式 [重复]
【发布时间】:2013-10-29 17:10:11
【问题描述】:

计算代数表达式 Z,其中 n 由用户输入。使用 2 个 for 循环来解决问题。

到目前为止我的代码:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            float sum = 0;

            int n = int.Parse(Console.ReadLine());

            for (int i = 1; i <= n; i++)
            {
                float p = 1;
                for (int k = 1; k <= i + 2; k++)
                {
                    p *= (3 * k + 2);
                }

                sum += p;
            }

            Console.WriteLine(sum);
            Console.ReadLine();
        }
    }
}

如果情况 3 和 4 返回 6200(这是错误的 + 相同),我会得到错误的结果,有时是相同的。

【问题讨论】:

    标签: c# algebra


    【解决方案1】:

    在第一个 for 循环中使用 &lt;= 而不是 &lt;,并使用 i++ 而不是 i+=2

    另外,您不需要使用float,因为结果总是一个整数。请改用long

    【讨论】:

    • 我这样做了,但我不再得到相同的结果,但是,我认为结果仍然错误?对于输入 2,我得到答案:6600。我认为答案是 30(如果我计算正确?)。
    • 没有。它得到了正确的解决方案。你错了。 :) wolframalpha.com/input/…
    【解决方案2】:

    我想这行是错误的:

    for (int i = 0; i < n; i += 2)
    

    应该是

    for (int i = 1; i <= n; i++)
    

    【讨论】:

    • 我已经这样做了,看看更新,结果又几乎一样了......
    猜你喜欢
    • 2013-11-08
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多