Ahs*_*ain 1 .net c# console-application
嗨,我正在读一本名为"Beginning Visual C#2012 Programming"的书,这本书在第4章的lopping部分中给出了以下的例子.
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在在线
Console.WriteLine("in {0} years{1} you'll have the balance of {2}.",totalYears, totalYears == 1 ? "" : "s", balance);
Run Code Online (Sandbox Code Playgroud)
我不明白为什么在一年中使用{1}意味着他们正在访问"",totalYears,totalYears == 1?"":"s""这段代码,为什么你要访问这段代码以及为什么他们不简单地写
Console.WriteLine("in {0} years you'll have the balance of {1}.",totalYears,balance);
Run Code Online (Sandbox Code Playgroud)
但是当我尝试通过上面的代码编译代码时,编译器会给出错误:
索引(从零开始)必须大于或等于零且小于参数列表的大小.
为什么会这样?可以解释一下吗?
这是一个错字,应该说:
Console.WriteLine("in {0} year{1} you'll have the balance of {2}.",totalYears, totalYears == 1 ? "" : "s", balance);
Run Code Online (Sandbox Code Playgroud)
我们的想法是把它说in 1 year...还是in 2 years...等笔者虽然犯了一个错误,并增加了一个额外的"s".