在 C# 中添加从 1 到 N 的数字 [英] Adding numbers from 1 to N in C#

查看:50
本文介绍了在 C# 中添加从 1 到 N 的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 编写代码并尝试添加数字 1 和 N 之间的所有数字,N 是在文本框中输入的数字.我正在这样做,至少尝试这样做,将其放入 while 循环中.

I'm writing code in C# and trying to add all of the numbers between the number 1 and N, N being the number that is inputted in a textbox. I'm doing this, at least trying to do this, by putting it into a while loop.

我之前已经添加了 2 个文本框之间的所有数字,但由于某种原因,我快把自己逼疯了,无法弄清楚这一点.我是一个初级程序员,所以请温柔.

I have added all the numbers between 2 textboxes before but for some reason I'm driving myself crazy and can't figure this out. I'm a beginning programmer so please be gentle.

任何帮助将不胜感激.

我尝试过的六千件事之一.我认为这让我陷入无限循环?

One of the six thousand things I've tried. I think this has me in an infinite loop?

       private void btnAddAll_Click(object sender, EventArgs e)
       {
           int n;
           int count = 0;
           int answer = 0;

           n = int.Parse(txtNum.Text);

           count = n;

           while (count >= 1)
           {
               answer = answer + count;
               count++;
           }
               lstShow.Items.Add("Sum = " + answer);
               lstShow.Text = answer.ToString();
       }

推荐答案

为什么不使用高斯公式.(N*(N+1))/2

Why not use Gauss formula. (N*(N+1))/2

private void btnAddAll_Click(object sender, EventArgs e)
{
     int n, answer;  
     n = int.Parse(txtNum.Text);
     answer = (n*(n+1))/2;
     lstShow.Items.Add("Sum = " + answer);
     lstShow.Text = answer.ToString();
}

这篇关于在 C# 中添加从 1 到 N 的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆