gpt4 book ai didi

c# - 代码有点困惑

转载 作者:太空宇宙 更新时间:2023-11-03 19:12:35 25 4
gpt4 key购买 nike

您好,我正在阅读一本名为 “Beginning Visual C# 2012 Programming” 的书,在这本书的第 4 章的循环部分下,他们给出了以下示例。

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

namespace ChapterFourExcerciseFour
{
class Program
{
static void Main(string[] args)
{
double balance, interestRate, targetBalance;
int totalYears = 0;

//reading balance from the console and saving it into the balance
Console.WriteLine("Please Enter your balance");
balance = Convert.ToDouble(Console.ReadLine());

//reading interesrrate from the console and saving it into tht interesrrate
Console.WriteLine("What is your current interest rate");
interestRate = Convert.ToDouble(Console.ReadLine());

//reading targetbalance from the console and saving it int the targetbalance
Console.WriteLine("What balancce would you like to have");
targetBalance = Convert.ToDouble(Console.ReadLine());

do
{
balance *= interestRate;
++totalYears;
}
while (balance < targetBalance);
Console.WriteLine("in {0} years{1} you'll have the balance of {2}.",totalYears, totalYears == 1 ? "" : "s", balance);
Console.ReadKey();
}
}
}

现在在排队

Console.WriteLine("in {0} years{1} you'll have the balance of {2}.",totalYears, totalYears == 1 ? "" : "s", balance);

我不明白为什么在年份附近使用 {1} 意味着他们正在访问 "",totalYears, totalYears == 1? "": "s""这段代码,你为什么访问这段代码,为什么他们不简单地写

Console.WriteLine("in {0} years you'll have the balance of {1}.",totalYears,balance);

但是当我尝试通过上面的行编译代码时,编译器给出了错误:

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

为什么会这样?谁能解释一下?

最佳答案

打错了,应该写成:

Console.WriteLine("in {0} year{1} you'll have the balance of {2}.",totalYears, totalYears == 1 ? "" : "s", balance);

想法是让它说 in 1 year...in 2 years... 等等。作者犯了一个错误,并添加了一个额外的“s”。

关于c# - 代码有点困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19518993/

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