【问题标题】:Debugging: System.DivideByZeroException: Attempted to to divide by zero [closed]调试:System.DivideByZeroException:试图除以零 [关闭]
【发布时间】:2019-03-22 12:23:44
【问题描述】:

我不明白为什么我会得到这个除以零的异常。一般来说,我对编程很陌生,无法弄清楚我做错了什么。抱歉,代码很长,我想我已经尽可能多地删除了它,但它仍然给出异常。 这是 C# 代码...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;


namespace CalculationApp
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
    public MainPage()
    {
        InitializeComponent();
        BreakEvenCalculation();
    }
    private void BreakEvenCalculation()
    {
        var purchaseprice = Decimal.Parse(PurchasePriceEntry.Text);
        var purchaseweight = Decimal.Parse(PurchaseWeightEntry.Text);
        var purchasefreight = Decimal.Parse(PurchaseFreightEntry.Text);
        var medicineimplants = Decimal.Parse(MedicineImplantsEntry.Text);
        var costofgain = Decimal.Parse(CostOfGainEntry.Text);
        var poundstillsell = Decimal.Parse(PoundsTillSellEntry.Text);
        var deathloss = Decimal.Parse(DeathLossEntry.Text);
        var saleweight = Decimal.Parse(SaleWeightEntry.Text);
        var salefreight = Decimal.Parse(SaleFreightEntry.Text);
        var breakeven = Decimal.Parse(BreakEvenEntry.Text);

        var purchasedollars = purchaseprice * purchaseweight;
        var feedcost = costofgain * poundstillsell;
        poundstillsell = saleweight - purchaseweight;

        var costs = (purchasedollars + purchasefreight + medicineimplants + feedcost + deathloss + salefreight);
        breakeven = costs / saleweight;             //throws exception.... System.DivideByZeroException: Attempted to divide by zero
        //breakeven = costs / (saleweight + 1);       //correctly equals 1.111302549965541
        //breakeven = costs * saleweight;           //correctly equals 2338125.00
        //breakeven = saleweight;                   //correctly equals 1450.00
        //breakeven = costs;                        //correctly equals 1612.50
        ////////////breakeven should equal  1.112068965517241
        BreakEvenEntry.Text = breakeven.ToString();
    }
    private void PurchasePriceEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void PurchaseWeightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void PurchaseFreightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void MedicineImplantsEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void CostOfGainEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void PoundsTillSellEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void DeathLossEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void SalePriceEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void SaleWeightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
    private void SaleFreightEntry_Completed(object sender, TextChangedEventArgs e)
    {
        BreakEvenCalculation();
    }
}

这里是 xaml 代码...

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="CalculationApp.MainPage"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:CalculationApp"
         xmlns:customentry="clr-namespace:CustomEntry">

<StackLayout Padding="0" BackgroundColor="AliceBlue" Orientation="Vertical">

    <Label Text="CalculationApp" TextColor="Black" FontAttributes="Italic" FontSize="Large" TextDecorations="Underline" Scale="1.5"
           Margin="0,15,0,10" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" VerticalOptions="CenterAndExpand"/>

    <Grid ColumnSpacing="0" RowSpacing="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width=".6*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Label Text="Purchase Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="0" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap"/>
        <Label Text="Purchase Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="1" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Purchase Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="2" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Medicine/Implants" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="3" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Cost of Gain" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="4" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Pounds Till Sell" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="5" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Death Loss" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="6" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Sale Price" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="7" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Sale Weight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="8" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />
        <Label Text="Sale Freight" TextColor="Black" FontAttributes="Bold" Margin="0,0,25,0" Scale="1.2"
               Grid.Column="0" Grid.Row="9" HorizontalTextAlignment="End" VerticalTextAlignment="Center" LineBreakMode="NoWrap" />

        <Entry x:Name="PurchasePriceEntry" Text="{Binding Source={x:Reference PurchasePriceStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" Keyboard="Numeric" ReturnType="Next" VerticalOptions="End" MaxLength="5"
                             TextChanged="PurchasePriceEntry_Completed"/>
        <Entry x:Name="PurchaseWeightEntry" Text="{Binding Source={x:Reference PurchaseWeightStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="1" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="PurchaseWeightEntry_Completed" />
        <Entry x:Name="PurchaseFreightEntry" Text="{Binding Source={x:Reference PurchaseFreightStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="2" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="PurchaseFreightEntry_Completed" />
        <Entry x:Name="MedicineImplantsEntry" Text="{Binding Source={x:Reference MedicineImpantsStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="3" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" 
                             TextChanged="MedicineImplantsEntry_Completed" />
        <Entry x:Name="CostOfGainEntry" Text="{Binding Source={x:Reference CostofGainStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="4" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" 
                             TextChanged="CostOfGainEntry_Completed" />
        <Entry x:Name="PoundsTillSellEntry" Text="1000" TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory"  TranslationX="3"
                             Grid.Column="1" Grid.Row="5" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center" IsEnabled="False" />
        <Entry x:Name="DeathLossEntry" Text="{Binding Source={x:Reference DeathLossStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="6" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="DeathLossEntry_Completed" />
        <Entry x:Name="SalePriceEntry" Text="{Binding Source={x:Reference SalePriceStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="7" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="SalePriceEntry_Completed" />
        <Entry x:Name="SaleWeightEntry" Text="{Binding Source={x:Reference SaleWeightStepper}, Path=Value}"  
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="8" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="SaleWeightEntry_Completed" />
        <Entry x:Name="SaleFreightEntry" Text="{Binding Source={x:Reference SaleFreightStepper}, Path=Value}" 
                             TextColor="DarkSlateGray" FontAttributes="Bold" BackgroundColor="Ivory" TranslationX="3"
                             Grid.Column="1" Grid.Row="9" HorizontalTextAlignment="Center" Keyboard="Numeric" VerticalOptions="Center"
                             TextChanged="SaleFreightEntry_Completed" />

        <Stepper x:Name="PurchasePriceStepper" Grid.Column="2" Grid.Row="0" HorizontalOptions="Center" VerticalOptions="Center"  Scale=".75" TranslationX="3" Maximum="5" Minimum=".01" Increment=".01" Value="1.75" />
        <Stepper x:Name="PurchaseWeightStepper" Grid.Column="2" Grid.Row="1" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="2000" Minimum="1" Increment="1" Value="550"/>
        <Stepper x:Name="PurchaseFreightStepper"  Grid.Column="2" Grid.Row="2" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
        <Stepper x:Name="MedicineImpantsStepper" Grid.Column="2" Grid.Row="3" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment=".25" Value="25.00"/>
        <Stepper x:Name="CostofGainStepper" Grid.Column="2" Grid.Row="4" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="3" Minimum="0" Increment=".01" Value="0.65"/>
        <Stepper x:Name="DeathLossStepper" Grid.Column="2" Grid.Row="6" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="500" Minimum="0" Increment="1" Value="20"/>
        <Stepper x:Name="SalePriceStepper" Grid.Column="2" Grid.Row="7" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5" Minimum="0" Increment=".01" Value="1.25"/>
        <Stepper x:Name="SaleWeightStepper" Grid.Column="2" Grid.Row="8" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="5000" Minimum="0" Increment="5" Value="1450.00"/>
        <Stepper x:Name="SaleFreightStepper" Grid.Column="2" Grid.Row="9" HorizontalOptions="Center" VerticalOptions="Center" Scale=".75" TranslationX="3" Maximum="100" Minimum="0" Increment=".25" Value="10"/>
    </Grid>

    <Grid Padding="10" ColumnSpacing="5" RowSpacing="10" VerticalOptions="FillAndExpand">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Label Text="Break Even" x:Name="BreakEvenLabel" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="0" Grid.Row="0"  HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
        <Label Text="Profit" TextColor="Black" FontSize="Medium" FontAttributes="Bold" Grid.Column="1" Grid.Row="0" HorizontalTextAlignment="Center" VerticalOptions="Center" LineBreakMode="NoWrap" />
        <Entry x:Name="BreakEvenEntry" Text="125" FontSize="Large" TextColor="Black" Grid.Column="0" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
        <Entry x:Name="ProfitEntry" TextColor="Black" FontSize="Large" Grid.Column="1" Grid.Row="1" FontAttributes="Bold" BackgroundColor="Ivory" IsEnabled="False" HorizontalTextAlignment="Center" VerticalOptions="Center" />
    </Grid>
</StackLayout>
</ContentPage>

异常发生在 C# 中的这一行...

breakeven = costs / saleweight;

如您所见,我尝试了几种不同的方法来更改代码以试图弄清楚发生了什么。在我看来,要获得除以零异常,销售权重必须为零,但如果我将代码更改为简单地读取......

breakeven = saleweight;

Xamarin.Forms BreakEvenEntry 给了我正确的销售权重...所以它不是零,对吗??

我错过了什么?我做错了什么??

提前感谢您的帮助!

【问题讨论】:

  • 你能提供一个minimal reproducible example吗?
  • 我必须假设您的SaleWeightEntry.Text 内容为零??
  • 您正在除以零,只需调试您的代码,找出原因并修复它。这确实是一个调试问题
  • 好的。调试时(不是通过表单输出)我确实得到了零(我正在学习!)。由于所有控件都已连接,因此我的代码无法真正分解为仅上传部分...我的 xamarin 表单条目使用绑定从步进器获取其值,因此在开始时并未明确赋予它们值。这可能是为什么?

标签: c# xamarin xamarin.forms


【解决方案1】:

'Cost' 被创建为浮点数或双精度数,需要显式定义为十进制以匹配您解析的十进制变量。

decimal costs = (purchasedollars + [...]

Here is a link 关于 C# 的整数与浮点除法:

“如果其中一个操作数是十进制,则另一个操作数既不能是浮点数也不能是双精度数,因为浮点数和双精度数都不能隐式转换为十进制。您必须将浮点数或双精度操作数显式转换为十进制类型。”

(与上述建议相反,您可以考虑将变量解析为双精度或浮点数。结果相同:浮点除法而不是整数除法。)

我试图重现您的错误,但无法重现。然而,我想起了在 Python 2.7 中找到similar error 的时间。

【讨论】:

  • 我将解析转换为双精度而不是十进制,并将“成本”转换为双精度,这解决了我的问题。谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 2011-07-29
相关资源
最近更新 更多