C递归程序打印所有偶数乘以2,以及打印多少个数字

时间:2016-06-27 23:27:45

标签: c recursion

我想知道你是否有人可以帮助这个递归程序,我需要一个偶数的数字,乘以2,然后打印它们,并打印它打印的次数。我的麻烦在于,如果我输入15628,我应该返回12416:3(1 5 6 2 8 = 6 * 12 = 12,2 * 2 = 4,8 * 2 = 16,12416:3)。我的问题是,它打印出16 4 12(以相反的方式,它实际打印16 | 4 | 12(102):3)?,我不明白为什么它打印102?请多多帮助,谢谢:)

[Console]::ForegroundColor = 'red'
[Console]::Error.WriteLine("An error occurred ... Have you tried rebooting?")
[Console]::ResetColor()

1 个答案:

答案 0 :(得分:1)

试试这个:

<Window.Resources>
                <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
                <Style x:Key="MyButtonStyle" TargetType="Button">
                    <Setter Property="OverridesDefaultStyle" Value="True"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="Button">
                                <Border Name="border" 
                                    BorderThickness="1"
                                    BorderBrush="DarkGray" 
                                    Background="{TemplateBinding Background}">
                                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                                </Border>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter TargetName="border" Property="BorderBrush" Value="Black" />
                                        <Setter Property="Foreground" Value="Red"/>
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
    </Window.Resources>

<Button Style="{StaticResource MyButtonStyle}" Content="Install" Command="{Binding InstallCommand}" Visibility="{Binding InstallEnabled, Converter={StaticResource BooleanToVisibilityConverter}}" Margin="150,30,30,22" Width="118" BorderBrush="#FF252424" FontSize="18" FontWeight="Bold" Foreground="White" FontFamily="Segoe UI Light" FontStretch="ExtraExpanded" Background="#FF4F4F4F"/>

总结问题评论,这个答案是一个补充(实际上,这是TO要求的例子):

  1. 第二个if块与第一个if是互补的(即覆盖所有第一个if将离开的情况),所以if实际上已经过时,其他第二个从未输入(幸运的是,因为没有修改任何n,pr或count,显然我们会以无休止的递归结束......)。另外,如果围绕计数++和printf(不包括递归,虽然!),内部缺少大括号,所以奇数也会被打印出来。
  2. 无需计算两次模数 - int rek(int n) { int result = 0; if (n != 0) { result = rek(n / 10); if(n % 2 == 0) { ++result; printf("%d", n % 10 * 2); } } return result; } int main() { int n; int count; scanf("%d", &n); count = rek(n); printf(" : %d", count); return 0; } 始终等于n % 10 % 2,因为10是2的倍数。
  3. 完全没有使用
  4. n % 2,所以放弃它
  5. 评估以最低有效数字开始,因此如果在递归调用之前立即打印出来,则与TO尝试实现的数字序列相比,反转得到的数字序列。所以首先需要递归调用,然后打印出结果。
  6. 打印需要移出递归函数的计数,因为我们颠倒了打印/递归顺序,然后先打印计数。
  7. 直接使用递归调用的结果会使count参数无关/过时,所以也将其删除。
相关问题