gpt4 book ai didi

c# - 返回以逗号分隔的前两个数组元素加起来等于 30 的字符串

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

我是一名新的 C# 程序员,目前遇到以下问题:

Given an array of numbers = 
[49, 71, 68, 26, 58, 64, 47, 16, 42, 53, 20, 15, 17, 45, 43, 52, 88, 65, 46, 82, 86,
69, 84, 56, 54, 28, 60, 32, 95, 29, 9, 79, 98, 51, 90, 36, 24, 62, 14, 91, 83, 3,
74, 30, 33, 6, 92, 40, 70, 2, 44, 31, 55, 12, 8, 89, 37, 72, 25, 81, 23, 100, 13,
87, 80, 18, 85, 5, 78, 10, 75, 41, 67, 94, 27, 96, 22, 73, 21, 63, 7, 34, 39, 61,
4, 19, 97, 93, 11, 35, 77, 76, 48, 57, 50, 99, 1, 59, 66, 38]

编写一个 C# 函数,它将返回数组中前两个数字的逗号分隔字符串,总和为 30 并立即退出。

我已经研究了一段时间,它看起来很简单,但这就是我所能想到的:

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

class Program
{
static void Main()
{
int[] array1 = { 49, 71, 68, 26, 58, 64, 47, 16, 42, 53, 20, 15, 17, 45, 43, 52, 88, 65, 46, 82, 86, 69, 84, 56, 54, 28, 60, 32, 95, 29, 9, 79, 98, 51, 90, 36, 24, 62, 14, 91, 83, 3, 74, 30, 33, 6, 92, 40, 70, 2, 44, 31, 55, 12, 8, 89, 37, 72, 25, 81, 23, 100, 13, 87, 80, 18, 85, 5, 78, 10, 75, 41, 67, 94, 27, 96, 22, 73, 21, 63, 7, 34, 39, 61, 4, 19, 97, 93, 11, 35, 77, 76, 48, 57, 50, 99, 1, 59, 66, 38 };
int sum1 = array1.Sum();
Console.WriteLine(sum1);
}
}

我知道我只是遗漏了一些小问题,我发现了类似的问题,但没有人为我解决这个问题。任何帮助或插入正确的方向将不胜感激。

最佳答案

功能:

static string GetFirstPairOf30(int[] data) {
for (int i = 0; i < data.Length; i++) {
for (int j = 0; j < data.Length; j++) {
if (i != j && data[i] + data[j] == 30) {
return String.Format("{0},{1}", data[i], data[j]);
}
}
}
throw new ArgumentException("Array does not contain pairs with sum 30");
}

用法:

   Console.WriteLine(GetFirstPairOf30(array1));

关于c# - 返回以逗号分隔的前两个数组元素加起来等于 30 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26986876/

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