注册 登录
编程论坛 C语言论坛

本题解法

xk2401594673 发布于 2020-04-05 19:46, 3574 次点击
从键盘输入一个正整数n,计算该数的各位数字之和并输出。例如输入5246,计算5+2+4+6=17并输出
11 回复
#2
sherlocked132020-04-05 19:56
#include <stdio.h>
#include <stdlib.h>
int main()
{
   int a;
   scanf("%d",&a);
   int b,c,d,e;
   int sum;
   b=a/1000;
   c=a/100%10;
   d=a/10%10;
   e=a%10;
   sum=b+c+d+e;
   printf("%d",sum);
}


就是一个分离各个数位的思想
#3
lin51616782020-04-05 21:32
字符串输入 处理起来很方便
程序代码:
#include <stdio.h>
int main()
{
    int count = 0;
    for(int n = '0'; n != '\n'; n = getchar())
        count += n - '0';
    printf("%d\n", count);
    return 0;
}
#4
smalluncle2020-04-06 00:58
还是楼上的代码看起来舒服,我好弱。


    int max=0 ;
    char str[32];
    printf("请输入您要计算的结果:\n");
    gets(&str);
   
    for (int i = 0; i < strlen(str); i++) {
        switch (str[i]) {
            case '1':
                max += 1;
                break;
            case '2':
                max+=2;
                break;
            case '3':
                max+=3;
                break;
            case '4':
                max+=4;
                break;
            case '5':
                max+=5;
                break;
            case '6':
                max+=6;
                break;
            case '7':
                max+=7;
                break;
            case '8':
                max+=8;
                break;
            case '9':
                max+=9;
                break;
            case '0':
                max+=0;
                break;
        }
    }
    printf("The max is %d \n",max);
#5
自学的数学2020-04-06 13:40
程序代码:
#include<stdio.h>
int main()
{
int n,sum=0;
scanf("%d",&n);
while(n)
{
sum += n%10;
n/=10;
}
printf("%d\n",sum);
return 0;
}
#6
opq20202020-04-06 20:21
额,不知道
#7
hbccc2020-04-06 20:50
用%10,然后累加
#8
fulltimelink2020-04-09 10:58
程序代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void main(void)
{
    int theNum = 0;
    scanf("%d", &theNum);
    int theResult = 0;
    while (theResult += (theNum%10),theNum /= 10) {}
    printf("%d\n", theResult);
}
#9
计算机好难啊2020-04-10 09:37
根据你所提出的问题,可以判断你还是个初学者。
5楼的答案最适合你
#include<stdio.h>
int main()
{
int n,sum=0;
scanf("%d",&n);
while(n)
{
sum += n%10;
n/=10;
}
printf("%d\n",sum);
return 0;
}
#10
fulltimelink2020-04-10 14:31
来个递归
程序代码:

unsigned binary_ascii_add(unsigned value) {
    unsigned quotient;
    unsigned sum = 0;
    quotient = value / 10;
    if (0 != quotient) {
        sum += binary_ascii_add(quotient);
    }
    sum += value % 10;
    return sum;
}
#11
return_02020-04-10 14:38
回复 10楼 fulltimelink
不要杀猪用牛刀吧。。。
#12
fulltimelink2020-04-10 14:56
回复 11楼 return_0
刚好复习到这个。。。  莫怪。。。
1