关于while语句和do while语句的问题

悠隼 2019-06-14 05:22:02
C#新人求解答:以下两个程式写法有什么区别?为什么第二个会提示错误:控制离开当前方法之前必须对 out 参数“interest”赋值。
我无法理解为什么第二个会错,不是也返回了interest值了吗?求高手解释。

第一个
/////////////////////////////////////
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
decimal x = 1000;
decimal y;
decimal z = Gain(x, 3, out y);
Console.WriteLine("本息合计:{0},最后一年利息:{1}", z, y);
Console.ReadLine();

}
public static decimal Gain(decimal x, int n, out decimal interest)
{
int i = 0;
do
{
interest = x * 0.08M;
x += interest;
i++;
}
while (i < n);
return x;
}
}
}
////////////////////////////////////////

第二个
////////////////////////////////////////
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
decimal x = 1000;
decimal y;
decimal z = Gain(x, 3, out y);
Console.WriteLine("本息合计:{0},最后一年利息:{1}", z, y);
Console.ReadLine();

}
public static decimal Gain(decimal x, int n, out decimal interest)
{
int i = 0;
while (i < n)
{
interest = x * 0.08M;
x += interest;
i++;
}

return x; //这里提示我错误:控制离开当前方法之前必须对 out 参数“interest”赋值。
}
}
}
/////////////////////////////////////////////////////////////////////
...全文
243 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
打老虎zz 2019-06-14
  • 打赏
  • 举报
回复
你的while() {}在编译器眼里是 不一定执行 他看起来并不想理解你的新想法
wanghui0380 2019-06-14
  • 打赏
  • 举报
回复
int i = 0; decimal interestx = 0; while (i < n) { interest = x * 0.08M; x += interestx; i++; interest = interestx; } return x; //这里提示我错误:控制离开当前 去掉红字,那是传递进来的参数,不要覆盖申明
悠隼 2019-06-14
  • 打赏
  • 举报
回复
版主大人,我加了interestx进去,还是这个提示~还是无法理解

int i = 0;
decimal interestx = 0;
while (i < n)
{
interest = x * 0.08M;
x += interestx;
i++;
interest = interestx;
}

return x; //这里提示我错误:控制离开当前方法之前必须对 out 参数“interest”赋值。
wanghui0380 2019-06-14
  • 打赏
  • 举报
回复
引用 4 楼 悠隼 的回复:
楼上3位的解释我理解了,但还有一个问题就是,我的decimal z 在调用这个方法的时候,已经给n赋值3了,所以会执行,这样interest不是就已经被赋值了吗?
编译器是静态检查,他并不知道你这个变量在运行期到底是什么,变量,变量----就是可变的量。编译器不假定那个一定是3. 也许你说你明明本次调用写的3,但这次本次调用。那个方法可能在你的程序里被在几百个地方调用,如果让编译器把这个几百个调用一起检查一道,我觉着你会疯。------------因为编译1次也许要1个小时
exception92 2019-06-14
  • 打赏
  • 举报
回复
在方法体Gain内,必须对out参数赋值,没有赋值编译器会认为是错误的。方法返回之前的逻辑可能不对interest赋值。 既然返回多个值,返回个数组/元组也可以,或者:
 decimal interestx = 0;
            while (i < n)
                ...........
 interest = interestx;
悠隼 2019-06-14
  • 打赏
  • 举报
回复
楼上3位的解释我理解了,但还有一个问题就是,我的decimal z 在调用这个方法的时候,已经给n赋值3了,所以会执行,这样interest不是就已经被赋值了吗?
  • 打赏
  • 举报
回复
do至少执行一次,while可能一次都没有,强大的编译器给你检测出来了
  • 打赏
  • 举报
回复
do是必定会执行 while是不一定会执行,不一定执行的,那赋值过程也就不一定存在
wanghui0380 2019-06-14
  • 打赏
  • 举报
回复
这是编译器检查 do 不管怎么样你都执行了{}里面的东西,所以interest 被赋值了 while 你有可能直接越过{}(假设n是0,i<n 一开始就不满足,这个循环根本就没执行),所以interest有可能从来就没被赋值

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧