C程序设计第五章习题

发布于:2024-05-13 ⋅ 阅读:(158) ⋅ 点赞:(0)

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+

网站公告

今日签到

点亮在社区的每一天
去签到