Fraction sum problem in C#

Asked

Viewed 311 times

2

Make a script to calculate and display the sum of the first "N" values of the sequence below. The value "N" will be typed (TextBox), should be positive, greater than zero, but less than fifty. If the value does not meet the restriction, send error message and request the value again. The sequence: 1/2, 2/3, 3/4, 4/5,... to N/(N+1)

To solve it, I created a Textbox and a button in Visual Studio, using C#.

I arrived at the following code:

namespace SomaFracoes
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
           int NSoma=0;
            double calculo =0;
            double number =0;

            if (int.TryParse(txtNum.Text, out NSoma) && NSoma <= 50 && NSoma > 0)
            {


                NSoma--;

                for (int i = 0; i < NSoma; i++)
                {

                    number =  Convert.ToDouble(i);
                    number++;
                    calculo += number /( number + 1);

                }

                MessageBox.Show(calculo.ToString("F"));

            }
            else
            {
                MessageBox.Show("Digite um número válido");


            }
            }

        }

    }

But I can’t get the right answer (example, if typed 3 in Textbox, according to my calculations should be shown 1.91 in MessageBox) do not know where is the problem of this code.

1 answer

2


There are several errors there, starting with the interpretation of the text. I solved it in 2 lines (I switched to console to make it universal and simple, but just change the count there by the Winforms variable and rewrite the window instead of the console):

using static System.Console;

public class Program {
    public static void Main() {
        if (int.TryParse("5", out var limite) && limite > 0 && limite < 50) for (var i = 1.0; i <= limite; i++) WriteLine($"{i/(i + 1):F2}");
        else WriteLine("Digite um número válido");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I organized the condition a little better, and had it validated up to 50 exclusively according to the statement. There is no reason to decrease 1 in the entered file. I improved the variable name.

Then I started the loop already in 1 and as double, there is no need to convert and increment anything, nor create so much variable, even further away from where they are used.

The statement is a little weird, but I understood that it should show the sequence of data. What is not clear in it is whether to do the bill or show a text with the fractions, I went to the account because you started like this and it makes some sense.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.