首页 > 解决方案 > C中的计数输出

问题描述

我的程序输入是 6,输出是6! = 6 x 5 x 4 x 3 x 2 x 1 = 720. 所以我想计算输出中的所有字符,包括“x”和空格字符。之后我想在输出上方打印 * 作为输出字符号。这是我用于阶乘的代码,但我找不到如何计算字符。

#include <stdio.h>

void fact_calc ( int n );

int main (void)
{
    int number;

    scanf ("%d", &number);
    printf ("%d! = %d x", number, number);
    fact_calc ( number );
}

void fact_calc ( int n )
{
    static long long int total = 1;

    if ( n != 2 && n >= 2 )
    {
        printf (" %d x", n - 1);
        total *= n;
        fact_calc ( n - 1 );
    }
    else
    {
        total *= 2;
        printf (" %d = %lld", n - 1, total);
    }
}

标签: ccountcharacter

解决方案


printf返回它打印的字符数。因此,您可以将调用的所有返回值相加printf得到总数。

这是您修改的代码:

#include <stdio.h>

void fact_calc ( int n, int *count );

int main (void)
{
    int number;
    int count = 0;

    scanf ("%d", &number);
    int t = printf ("%d! = %d x", number, number);
    if (t > 0) count += t;
    fact_calc ( number, &count );
    printf("\nTotal chars printed: %d\n", count);
}

void fact_calc ( int n, int *count )
{
    static long long int total = 1;

    if ( n != 2 && n >= 2 )
    {
        int t = printf (" %d x", n - 1);
        if (t > 0) *count += t;
        total *= n;
        fact_calc ( n - 1, count );
    }
    else
    {
        total *= 2;
        int t = printf (" %d = %lld", n - 1, total);
        if (t > 0) *count += t;
    }
}

推荐阅读