看看数字a是否比b更接近于c

时间:2016-06-09 13:13:49

标签: php function math integer

我目前正在尝试创建一个函数,可以判断数字a是否接近c而不是数字bc

我尝试过这样的比较:(从a获取bc并进行比较)

$c = 10;
$b = 2;
$a = 3;

$b_check = $c - $b; // = 8.
$a_check = $c - $a; // = 7.

在我的脑海中,我认为无论数字(ab)是否更小都意味着它将更接近c,尽管使用正整数,但是当它出现负整数时,它给出了完全错误的结果。

我想知道在in-built function中是否有PHP或者是否有更好的数学方法来实现这个目标?

2 个答案:

答案 0 :(得分:2)

If (a - c) * (a - c) < (b - c) * (b - c)会这样做。这样可以解决负数问题,这也是我们老猫在C中做到这一点的方式。

否则你可以使用Math.abs(a - c) < Math.abs(b - c)可以对某些类型更快,但你需要注意不要溢出你的类型和那里& #39;对于某些类型也可能产生毁灭性的环绕效果。

描述它。

答案 1 :(得分:1)

绝对值最小的那个总是最接近的。您正在考虑数字线,但如果您了解2D或3D空间中的矢量,则更容易想象。然后两点之间的距离是它们的分量之差的平方和的平方根。 1D案例是两个组件为零的特殊情况。

cs Code
___________

List<Audit_Group> groupSectionList = e.Parameter as List<Audit_Group>;
lbGroupSection.ItemsSource = groupSectionList; // lbGroupSection is the ListBox

.xaml code
_________________
<ListBox x:Name="lbGroupSection" Foreground="Black" Margin="6" HorizontalAlignment="Left" VerticalAlignment="Center" BorderThickness="1" Width="auto">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <!--<Border BorderBrush="Black" BorderThickness="1">-->
                            <!--ONE ROW-->
                            <StackPanel VerticalAlignment="Center">
                                <Grid Background="WhiteSmoke">
                                    <TextBlock Foreground="Black" Margin="5,0,0,0" x:Name="tbSectionName" TextWrapping="Wrap" Text="{Binding Section_Name}" FontSize="20"/>
                                </Grid>
                                <Border BorderBrush="Black" BorderThickness="1">
                                    <Grid Background="White">
                                        <Grid.ColumnDefinitions>
                                           <ColumnDefinition Width="270"></ColumnDefinition>
                                           <ColumnDefinition Width="100"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <TextBlock Grid.Column="0" HorizontalAlignment="Left" Foreground="Black" Margin="5,0,0,0" x:Name="tbGroupName" Text="{Binding Group_Name}" FontSize="20"/>
                                     <ToggleSwitch x:Name="tsGroup" Foreground="WhiteSmoke" Grid.Column="1" Toggled="tsGroup_Toggled" Style="{StaticResource ToggleSwitchButtonStyle1}" /> /* How to make it On/Off based on the DB field value */
                                 </Grid>
                              </Border>
                          </StackPanel>
                        <!--END ONE ROW-->
                   <!--</Border>-->
               </DataTemplate>
       </ListBox.ItemTemplate>
</ListBox>