Skip to main content
 首页 » 编程设计

c#之有什么方法可以使用循环重复此过程两次

2024年02月24日17xing901022

有没有什么办法可以使用循环(for, while, do-while)将下面的过程循环两次,但是将循环第二次迭代的结果存储在两个新变量中,然后创建第二个ComplexNumber使用第二次迭代中的那些变量值的对象?

Console.Write("Real part: "); 
double realValue = double.Parse(Console.ReadLine()); 
 
Console.Write("Complex part: "); 
double complexValue = double.Parse(Console.ReadLine()); 
 
ComplexNumber firstComplex = new ComplexNumber(realValue, complexValue); 

请您参考如下方法:

for 循环中的局部作用域使我们不必每次都需要唯一的变量。

ComplexNumber[] complexNumbers = new ComplexNumber[2]; 
 
for (int i = 0; i < complexNumbers.Length; i++) 
{ 
        Console.Write("Real part: "); 
        double realValue = double.Parse(Console.ReadLine()); 
 
        Console.Write("Complex part: "); 
        double complexValue = double.Parse(Console.ReadLine()); 
        complexNumbers[i] = new ComplexNumber(realValue, complexValue); 
}