c语言例题,逐个打印数字

今天来分享个比较简单的程序例题,也是比较经典的一个新手例题,逐个打印输入的数字。我们直接从主函数看起,先定义一个num变量,同时变量的类型是unsigned int,这个类型的意思是无符号的整型变量,unsigned(无符号)是用来修饰int的,说明了num这个变量只能是正数,然后我们用scanf输入想要的数字,进入print函数中打印;而在print函数中,运用一个if语句,通过/号和%号来输出每一个数位的数字。

当然,一般刚接触c语言的人会比较好奇,这里只有一个if语句到底是怎么实现把所有的数字都打印出来的?这里其实隐藏着一种方法,那就是反复的调用print函数,在c语言中有一个对这种编程方式的称呼,那就是递归方式。

主函数和打印函数

 

在C语言编程学习过程中,例题资源是非常重要的实践材料。以下是根据已有资料整理的几个典型例题及解析: ### 1. 成绩等级转换 该问题要求使用条件运算符将成绩分数转换为对应的等级(A、B、C)。程序通过判断输入的分数是否大于等于90、60-89之间或低于60分,分别用字符'A'、'B'和'C'表示[^3]。 ```c #include <stdio.h> int main() { int score; char grade; printf("Please input a score: "); scanf("%d", &score); grade = (score >= 90) ? 'A' : ((score >= 60) ? 'B' : 'C'); printf("%d belongs to %c\n", score, grade); return 0; } ``` ### 2. 最大公约数与最小公倍数 此问题要求输入两个正整数m和n,计算它们的最大公约数和最小公倍数。程序使用辗转相除法来求解最大公约数,并利用公式`最小公倍数 = m * n / 最大公约数`进行计算[^3]。 ```c #include <stdio.h> int gcd(int a, int b) { while (b != 0) { int temp = b; b = a % b; a = temp; } return a; } int main() { int m, n; printf("Enter two integers: "); scanf("%d %d", &m, &n); int greatest_common_divisor = gcd(m, n); int least_common_multiple = m * n / greatest_common_divisor; printf("GCD: %d\n", greatest_common_divisor); printf("LCM: %d\n", least_common_multiple); return 0; } ``` ### 3. 输入三个整数并按从小到大输出 该问题要求输入三个整数x、y、z,并按照从小到大的顺序输出。程序通过多次比较和交换操作,确保最终的顺序是正确的[^4]。 ```c #include <stdio.h> int main() { int x, y, z, temp; printf("Enter three integers: "); scanf("%d %d %d", &x, &y, &z); if (x > y) { temp = x; x = y; y = temp; } if (x > z) { temp = x; x = z; z = temp; } if (y > z) { temp = y; y = z; z = temp; } printf("Sorted order: %d %d %d\n", x, y, z); return 0; } ``` ### 4. 分解质因数 该问题要求输入一个整数n,并将其分解为质因数乘积的形式。程序通过从2开始逐步尝试除以每个可能的因数,直到n变为1为止[^2]。 ```c #include <stdio.h> int main() { int n; printf("Enter an integer: "); scanf("%d", &n); printf("Prime factors: "); for (int i = 2; i <= n; i++) { while (n % i == 0) { printf("%d ", i); n /= i; } } printf("\n"); return 0; } ``` ### 5. 行、单词和字符计数 该问题要求对输入的文本进行统计,包括行数、单词数和字符数。程序通过读取输入并逐个分析每个字符来实现这一功能[^5]。 ```c #include <stdio.h> #include <ctype.h> int main() { int c, nl = 0, nw = 0, nc = 0, in_word = 0; while ((c = getchar()) != EOF) { ++nc; if (c == '\n') ++nl; if (isspace(c)) { if (in_word) { in_word = 0; ++nw; } } else { in_word = 1; } } if (in_word) ++nw; // Count the last word if input doesn't end with space printf("Lines: %d\nWords: %d\nCharacters: %d\n", nl, nw, nc); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值