gpt4 book ai didi

c# - 计算 *newb* 之外的数组的总和

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:11 24 4
gpt4 key购买 nike

我已经想出了如何做我需要做的大部分事情。我意识到 for 循环中使用的变量在循环外是不可访问的,但我需要显示用户输入的整数的总和。所以,

第 1 步:要求用户输入整数个数。

第 2 步:获取每个整数。

第 3 步: 然后显示所有输入。

第 4 步: 应该有第 3 步的总和...那就是

我的问题在哪里。

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

namespace Dynamic_Entry
{
class Program
{
static void Main()
{
Console.Write("How many integers are in your list? ");
int k = Convert.ToInt32(Console.ReadLine());
int[] a = new int[k];
int sum = 0;

for (int i = 0; i < a.Length; i++)
{
Console.Write("Please enter an integer: ");
a[i] = Convert.ToInt32(Console.ReadLine());
}
for (int n = 0; n < a.Length; n++)
{
Console.WriteLine("{0, 5}", a[n]);
}
Console.WriteLine("-----");

sum += [] a;
Console.Write("{0, 5}", sum);
Console.ReadLine();
}
}
}

关于如何从循环外获取总和的任何帮助?如果我将连字符线放在最后一个循环中,它会在每个数字之后继续放置线......我只需要最后的线,以及它下面的总和。谢谢!

最佳答案

因为你可以使用 linq,所以用波纹管替换总和

 Console.WriteLine("-----");
sum = a.Sum();
Console.Write("{0, 5}", sum);

关于c# - 计算 *newb* 之外的数组的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18009383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com