调试:System.DivideByZeroException:试图除以零

时间:2019-03-19 02:17:02

标签: c# xamarin xamarin.forms

我不知道为什么我得到零除的异常。我一般对编程都是新手,无法弄清楚我做错了什么。对不起,冗长的代码,我想我已经尽可能多地删除了它,但仍然给出了异常。 这是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给我正确的销售权重...所以它不为零吧?

我想念什么?我在做什么错??

感谢您的提前帮助!

1 个答案:

答案 0 :(得分:2)

“费用”被创建为浮点数或双精度数,需要明确地定义为十进制,以匹配解析的十进制变量。

decimal costs = (purchasedollars + [...]

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

  

“如果一个操作数是十进制,则另一个操作数既不能是float也不是double,因为float和double都不能隐式转换为十进制。必须将float或double操作数显式转换为十进制类型。”

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

我试图重现您的错误,但无法执行。但是,让我想起了在Python 2.7中我找到一个similar error的时间。