Calculate the algebraic expression in C# [closed]

狂风中的少年 提交于 2019-12-02 23:54:47

问题


Calculate the algebraic expression Z, for which n is inputted by user. Use 2 for loops to solve the problem.

My code so far:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            int n, k = 1;
            double z;
            float sum, p;
            n = Console.Read();

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

                for (int j = 0; j < n; j++)
                {
                    p *= (3 * k + 2);
                }

            }

        }
    }
}

I'm totally stack in the for loops... any help is appreciated.


回答1:


  • p has to be initialized to 1 as 0 * X == 0
  • Also i and j (why not k) have to be initialized to 1 as it is required by your formula
  • You have to sum up the products after the products where calculated as you would add 1 to the correct result otherwise and you would not add the last calculated product

So the code below should give the correct result:

        float sum = 0;

        int n = Console.Read();

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

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

          sum += p;
        }


来源:https://stackoverflow.com/questions/19662357/calculate-the-algebraic-expression-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!