You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#入门代码报错:未识别变量answer,求修复方法

C#代码修正:解决未识别变量“answer”的问题

你的代码有两个关键错误导致程序无法识别answer变量:

  1. 未声明变量:C#是强类型语言,使用变量前必须先声明其类型,answer用来存储用户输入的字符串,需要先声明string answer;。
  2. 错误的赋值写法:Console.ReadLine是方法,调用时必须加括号(),而且赋值方向反了,应该是把方法返回的输入值赋值给answer,而非反过来写Console.ReadLine = answer;。

修正后的完整代码如下:

using System;
 
namespace MyApp 
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Double num01;
            Double num02;
            Double num03;
            // 声明string类型的answer变量
            string answer;

            Console.WriteLine("Do you want to find the average of three numbers?");

            // 正确调用Console.ReadLine()并赋值给answer
            answer = Console.ReadLine();
            
            if (answer == "Yes")
            {
                Console.Write("Ok, give me a number: ");
           
                num01 = Convert.ToDouble( Console.ReadLine() );
 
                Console.Write("Give me another number: ");
 
                num02 = Convert.ToDouble( Console.ReadLine() );

                Console.Write("And just one more: ");

                num03 = Convert.ToDouble( Console.ReadLine());

                Double result = (num01 + num02 + num03 ) / 3;
            
                Console.WriteLine("The result is: " + result);
           
                Console.ReadKey();
            }
            else
            {
                Console.Write("Oh, ok.");
                Console.ReadKey();
            }
        }
    }
}

额外提示:可以给answer变量添加空值判断,比如if (!string.IsNullOrEmpty(answer) && answer == "Yes"),避免用户直接回车导致的空字符串问题。

内容的提问来源于stack exchange,提问作者adamforshadom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 23:45:40