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.
- If it is, output the string
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
相关产品推荐
相关产品推荐

