C程序设计第五章习题

本文详细介绍了C语言编程的一些经典习题,包括最大公约数和最小公倍数的计算,字符统计,特殊数组的前n项和,水仙花数,完数,数列求和,皮球落地反弹问题,猴子吃桃问题,图形输出以及比赛选人问题的解决方案,每个问题都附带了代码和输出结果。
摘要由CSDN通过智能技术生成

5.3 最大公约数和最小公倍数

分析:

参考C程序设计第二章习题(下)-CSDN博客

代码:

#include "stdio.h"
 
void main() {
 
    int m = 0;
    int n = 0;
    printf("Please input tow numbers:");
    scanf("%d,%d", &m, &n);
 
    int i = 1;
    int x = 0;
    int y = 0;
    while(i <= m && i <= n) {
        if(m%i == 0 && n%i == 0) x = i;
        i++;
    }

    i = m;
    while(i >= m || i >= n) {
        if(i%m == 0 && i%n == 0) {
            y = i;
            break;
        }
        i++;
    }
 
    printf("the max common divisor of %d and %d is %d\n", m, n, x);

    printf("the min common divisor of %d and %d is %d", m, n, y);
}

输出结果:

 5.4 统计字符个数

 代码:

#include "stdio.h" 

int getStrLength(char *str) {
    int i = 0;
    while(str[i]) {
        i++;
    }
    return i;
}

void main() {
    //char *str; this will error, because it has not space. how to initalize?
    char str[100];//it has 100 8-bit space with '\0'

    printf("Please input a string:");
    //scanf("%s", str);//scanf无法接收空格字符
    fgets(str, sizeof(str), stdin);//fgets接收了回车键
    //int length = sizeof(str);//数组长度=100,而不是字符串的长度

    //printf("Please input a string:%d,%c,", length, str[sizeof(str)-1]);
    int length = getStrLength(str);
    str[length-1] = '\0';
    printf("Now output a string:%s\n", str);

    int i = 0;

    int j = 0;//count number
    int k = 0;//count charactor
    int l = 0;//count space
    int m = 0;//other chars
    while (str[i])
    {
        if(str[i] >= '0' && str[i] <= '9') {
            j++;
        } else if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z') {
            k++;
        }else if(str[i] == ' ') {
            l++;
        } else {
            m++;
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值