C#报错:赋值运算符左侧必须是变量、属性或索引器的解决求助
问题修复说明
错误原因
- for循环语法错误:C#的for循环三个部分必须用分号
;分隔,不是逗号,;而且你代码里的变量a未定义,程序无法识别循环次数。 - 赋值左操作数非法:
Math.Round(input)返回的是临时计算结果,不属于变量、属性或索引器,不能直接在它后面使用*=赋值操作,必须把计算结果存回input变量。
修正后的代码
Console.WriteLine("input x:"); int inputx = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("input y:"); double y = double.Parse(Console.ReadLine()); // 补充输入循环次数a Console.WriteLine("input loop count a:"); int a = Convert.ToInt32(Console.ReadLine()); double input = inputx; // 修正for循环语法 for (int i = 0; i < a; i++) { // 先对input取整,再乘以y,将结果重新赋值给input input = Math.Round(input) * y; } Console.WriteLine("Value output: {0}", input);
关键修正点
- 把错误的
for (int i = 0, i < a, i++)改为标准C#循环格式for (int i = 0; i < a; i++)。 - 新增循环次数
a的输入步骤,解决原代码中a未定义的问题。 - 将
Math.Round(input) *= y;调整为input = Math.Round(input) * y;,通过变量接收计算结果,符合C#的赋值规则。
内容的提问来源于stack exchange,提问作者elizac
相关产品推荐
相关产品推荐

