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

C#四则运算任务除数为0时触发‘调用目标抛出异常’错误求助

Fixing the Divide-by-Zero Error in Your C# Program

Hey there! That error you're seeing happens because when the second input is 0, your code is trying to do integer division by zero—and C# throws a DivideByZeroException when that happens. That's exactly what's causing the "Exception has been thrown by the target of an invocation." message.

Let's fix this by adding a simple check before trying to calculate the quotient. Here's how to approach it step by step:

  • First, read both input lines and convert them to integers.
  • Calculate the sum, difference, and product normally—these don't have issues with zero.
  • For the quotient, check if the second number is 0 first:
    • If it is, output the string "Can't divide by zero!"
    • If it's not, compute the division as usual.

Fixed Code Example

using System;

class Program
{
    static void Main()
    {
        // Read the two input integers
        Console.WriteLine("Enter first number:");
        int num1 = int.Parse(Console.ReadLine());
        
        Console.WriteLine("Enter second number:");
        int num2 = int.Parse(Console.ReadLine());
        
        // Calculate sum, difference, product
        int sum = num1 + num2;
        int difference = num1 - num2;
        int product = num1 * num2;
        
        // Handle quotient with zero check
        string quotientResult;
        if (num2 == 0)
        {
            quotientResult = "Can't divide by zero!";
        }
        else
        {
            // Use integer division since inputs are integers
            int quotient = num1 / num2;
            quotientResult = quotient.ToString();
        }
        
        // Output all results
        Console.WriteLine($"{sum}, {difference}, {product}, {quotientResult}");
    }
}

Let's Test It

  • Test Case 1: Input 12 and 4
    Output: 16, 8, 48, 3 (matches your example)
  • Test Case 2: Input 12 and 0
    Output: 12, 12, 0, Can't divide by zero! (no exceptions, works as expected)

The key here is that we never attempt to divide by zero—we catch that case first and skip the division entirely. That prevents the exception from being thrown in the first place.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:40:57