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.