【问题标题】:C# giving different value than expected [duplicate]C#给出的值与预期不同[重复]
【发布时间】:2020-09-04 16:50:17
【问题描述】:

我刚开始学习 C#,遇到了这个问题: 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_CSharp_
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the number: ");
            double num = Console.Read();
            
            Console.WriteLine("Result = " + num*num);
            
        }        
        
    }
}

当我输入时:10 这是输出:

Enter the number:
10
Result = 2401
Press any key to continue . . .

请帮忙。

我使用 Visual Studio 2019(社区版)

【问题讨论】:

    标签: c#


    【解决方案1】:

    Console.Read() 为您提供下一个字符值(即:它为您提供有效的 char 值或 -1),而不是下一个输入数字的值。

    您必须使用 Console.ReadLine() 并使用 double.TryParse(string, out double) 解析它:

    Console.WriteLine("Enter the number: ");
    // Get the next line input
    string input = Console.ReadLine();
    // Try to parse it as a double
    if (double.TryParse(input, out double num)) {
        // On true we have a number
        Console.WriteLine("Result = " + num*num);
    } else {
        // On fail we couldn't parse it.
        Console.WriteLine("Error, please input a number.");
    }
    

    【讨论】:

    • 详细说明:它正在读取输入的 1 的字符值,因此 OP 得到 49 * 49。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 2018-04-29
    相关资源
    最近更新 更多