新手c语言入门题目分享(九)

每天练习3道题,你也可以学会c语言

1.计算水仙花数(即每位数字的立方和等于该数本身)

#include <stdio.h>  

int main() {  
    int num;  
    printf("请输入一个三位数: ");  
    scanf("%d", &num);  
    
    if (num < 100 || num > 999) {  
        printf("请输入有效的三位数\n");  
        return 0;  
    }  
    
    int hundreds = num / 100;  
    int tens = (num / 10) % 10;  
    int units = num % 10;  
    
    if (num == (hundreds * hundreds * hundreds + tens * tens * tens + units * units * units)) {  
        printf("%d 是水仙花数\n", num);  
    } else {  
        printf("%d 不是水仙花数\n", num);  
    }  
    return 0;  
}

2.计算数组的中位数

#include <stdio.h>  
#include <stdlib.h>  

int compare(const void *a, const void *b) {  
    return (*(int *)a - *(int *)b);  
}  

int main() {  
    int n;  
    printf("请输入数组的大小: ");  
    scanf("%d", &n);  
    
    int arr[n];  
    printf("请输入 %d 个整数: ", n);  
    for (int i = 0; i < n; i++) {  
        scanf("%d", &arr[i]);  
    }  
    
    // 排序  
    qsort(arr, n, sizeof(int), compare);  
    
    double median;  
    if (n % 2 == 0) {  
        median = (arr[n / 2 - 1] + arr[n / 2]) / 2.0;  
    } else {  
        median = arr[n / 2];  
    }  
    
    printf("中位数是: %.2f\n", median);  
    return 0;  
}

3.计算字符串中单词的个数

#include <stdio.h>  
#include <string.h>  
#include <ctype.h>  

int main() {  
    char str[100];  
    int count = 0;  
    int inWord = 0;  
    
    printf("请输入一个字符串: ");  
    fgets(str, sizeof(str), stdin);  
    str[strcspn(str, "\n")] = 0; // 去掉换行符  
    
    for (int i = 0; i < strlen(str); i++) {  
        if (isspace(str[i])) {  
            inWord = 0;  
        } else {  
            if (inWord == 0) {  
                count++;  
                inWord = 1;  
            }  
        }  
    }  
    
    printf("单词的个数是: %d\n", count);  
    return 0;  
}

每天不定时分享一些c语言题目和32项目,如果喜欢就点点关注吧!!!!大佬们

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值