好的,此刻我自己是编程新手并慢慢学习。目前我正在学习编程课程以帮助更好地理解编程。我遇到了一个困扰我的问题。
现在虽然我可以用与我提供的相比不同的方式和方式完成作业。我的问题是,为什么会发生这种情况?我没有得到任何错误,所以,唯一发生的事情是在输入控制台Fezzes之后。我想知道我做错了什么。
static void Main(string[] args)
{
double[] Population = new double[6];
string[] Years = { "2", "3", "4", "5", "6", "7" };
double GrowthPercentage = 0.0;
double MathPercentage = 0.0000;
double ActualGrowth = 0.0;
int WhileCounter = 0;
//Ask user for Population of Roarkville
Console.WriteLine("Enter the Population of RoarkVille: ");
//Read Population and store
Population[0] = Convert.ToDouble(Console.ReadLine());
//Ask user for Growth percentage
Console.WriteLine("Enter the Growth percentage ");
//Read Growth Percentage
GrowthPercentage = Convert.ToDouble(Console.ReadLine());
//Calculation of Growth Percentage: Growth Percentage/100 = Math Percentage
MathPercentage = GrowthPercentage / 100;
//ActualGrowth = Population * Math Percentage
//Population2 = ActualGrowth + Population
while (WhileCounter < 5)
{
ActualGrowth = Population[WhileCounter] + MathPercentage;
WhileCounter++;
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
//Display 2012 Population
//Display 2013 Population
//Display 2014 Population
//Display 2015 Population
//Display 2016 Population
//Display 2017 Population
Console.ReadLine();
}
答案 0 :(得分:3)
所以当您使用此代码输入增长百分比时会发生什么:
while (Counter < 5)
{
ActualGrowth = Population[Counter] + MathPercentage;
Counter++;
Population[Counter] = ActualGrowth + Population[Counter--];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
您输入的数字在增长百分比上将是无限的:
这个也可以帮助你
while (Counter < 5)
{
ActualGrowth = Population[Counter] + MathPercentage;
Counter++;
Population[Counter] = ActualGrowth + Population[Counter-1];
}
for (int i = 0; i < Population.Length; i++)
{
Console.WriteLine("Population of 201{0:d}", Years[i]);
Console.WriteLine(Population[i]);
}
答案 1 :(得分:2)
++运算符会更改变量的实际值,因此WhileCounter++
会将变量增加1
- 运算符执行相同操作,这不是您想要在行
中执行的操作Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
相反,请使用WhileCounter - 1
,如此
Population[WhileCounter] = ActualGrowth + Population[WhileCounter - 1];
答案 2 :(得分:0)
WhileCounter++;
Population[WhileCounter] = ActualGrowth + Population[WhileCounter--];
就循环而言,WhileCounter
的值永远不会改变。在循环体中,您递增WhileCounter
并继续立即递减它,因此条件WhileCounter < 5
始终为真。
你也可以写
int WhileCounter = 0;
while(WhileCounter < 5)
{
WhileCounter += 1; // WhileCounter == 1
WhileCounter -= 1; // WhileCounter == 0
}
// aint never gunna happen
答案 3 :(得分:0)