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

C#方法实现两数相乘结果异常的问题求助

问题分析与解决方案

核心问题

你的代码中多余的 Console.Read(); 是导致计算结果错误的根本原因,它会破坏输入缓冲区内容,让后续 Multiply() 方法读取的输入并非你实际输入的数字。

具体原因

输入完名字按下回车键后,输入缓冲区会残留回车相关字符(\r\n)。Console.Read() 仅读取单个字符,剩余字符会留在缓冲区。当 Multiply() 调用 Console.ReadLine() 时,第一个 ReadLine() 会直接读取到空字符串或截断内容,最终解析出的数字和你输入的54、19不符,导致计算结果异常(比如出现-15这类错误值)。

修复方案

直接删除那行多余的 Console.Read();,如果需要等待用户按下回车再继续,可替换为 Console.ReadLine()。

修正后的代码示例

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.BackgroundColor = ConsoleColor.DarkRed;
        Console.Clear();
        Console.WriteLine("Please enter your name and I will tell you how many letters your name has!");
        string name = Console.ReadLine();
        Count(name);
        Console.WriteLine("Now tell me two numbers and I will multiply them!");

        try
        {
            Multiply();
        }
        catch (FormatException)
        {
            Console.WriteLine("You must enter a number!");
        }
    }

    public static void Count(string name)
    {
        Console.WriteLine("Your name has {0} letters!", name.Length);
    }

    public static void Multiply()
    {
        string firstNum = Console.ReadLine();
        string secondNum = Console.ReadLine();
        int num = Int32.Parse(firstNum);
        int num1 = Int32.Parse(secondNum);
        int result = num * num1;
        Console.WriteLine("The result is {0}", result);
    }
}

额外优化建议

为更优雅处理输入验证,建议用 int.TryParse() 替代直接的 Int32.Parse(),无需依赖try-catch块:

public static void Multiply()
{
    Console.WriteLine("Enter first number:");
    if (!int.TryParse(Console.ReadLine(), out int num))
    {
        Console.WriteLine("Invalid first number!");
        return;
    }

    Console.WriteLine("Enter second number:");
    if (!int.TryParse(Console.ReadLine(), out int num1))
    {
        Console.WriteLine("Invalid second number!");
        return;
    }

    int result = num * num1;
    Console.WriteLine("The result is {0}", result);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:50:31