【发布时间】:2021-05-07 01:35:32
【问题描述】:
我学习了几个 Java 课程,在学习之后了解到 C# 非常相似,我正在尝试通过将 Java 中的简单程序转换为 C# 来学习。到目前为止,它在简单的数学问题和打印到控制台方面进展顺利,但现在我开始使用数组和列表,但我似乎没有做正确的事情。我的代码看起来应该可以工作,并且 Visual Studio 2019 中的描述符看起来一切都应该按照我认为的方式运行。但它不会打印出与我的 Java 代码相同的有意义的数据。第一个 Java。
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Main {
//Max number method finds the max number of an array list
public static double largest(ArrayList x){
double max = (double) x.get(0);
for (int i =1; i<(double)x.size(); i++){
if ((double)x.get(i) > max){
max = (double)x.get(i);
}
}
return max;
}
public static void main(String[] args){
ArrayList<Double> numbers = new ArrayList<>();
DecimalFormat f = new DecimalFormat("##.00");
for (int x=0; x<40; x++){
numbers.add(
Double.valueOf(
f.format(Math.random()*100 - 1)));
}
System.out.println(numbers);
System.out.println(largest(numbers));
}
}
现在是 C#
using System;
using System.Collections.Generic;
namespace Arrays
{
class Program
{
public static double largest(Array x)
{
double max = (double)x.GetValue(0);
for(int i = 1; i<x.Length; i++)
{
if ((double)x.GetValue(i) > max)
{
max = (double)x.GetValue(i);
}
}
return max;
}
static void Main(string[] args)
{
Random rand = new Random();
List<double> numbers = new List<double>();
for(int x=0; x<40; x++)
{
numbers.Add(
Math.Round(
rand.NextDouble()));
}
Console.WriteLine(numbers);
Console.WriteLine(largest(numbers.ToArray()));
}
}
}
我知道语法会与任何其他两种语言不同,但我认为这会起作用。自学 C#,如果这看起来过于基础,我深表歉意。
【问题讨论】:
-
Java 和 C# 的相似之处更多是结构性和宏观性,而不是它们如何将列表输出到控制台的具体细节。