c - 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);
}
}
解决方案
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;
}
}
推荐阅读
- c++ - vscode c++ 代码格式化在开括号后不会加空格
- python - 如何在不改变格式的情况下从 for 循环中输出日期时间变量?
- reactjs - 前端过滤 React JS
- java - 禁用登录 org.apache.httpcomponents
- reactjs - ReactJS 道具:当父组件渲染时,并非所有道具都显示在组件中
- c# - C# 将 Mock 对象传递给验证/检查参数类型的类
- flutter - 如何在 DropdownButton 中制作子级别
- java - 使用 JNA 和 DLLExport 将结构数组从 Java 传输到 C#
- powershell - ForEach-Object 在子文件夹中查找
- ios - Flutter:在 iOS 模拟器 Firebase 中失去与设备的连接