简体   繁体   English

我应该从这段代码中改变什么

[英]what thing i should change from this code

I want to make a program to count the sum of digits in a string but only using stdio.h but the program needs to count until its less than 10 so the example you input 56 it would be 5+6=11 then 1+1=2 and so on我想制作一个程序来计算字符串中的数字总和,但只使用stdio.h但程序需要计数直到它小于 10 所以你输入 56 的例子是5+6=11然后1+1=2以此类推

here's my code.这是我的代码。 For now I'm just confused how to check if its whether more than 9 or not现在我只是很困惑如何检查它是否超过 9

#include<stdio.h>

int plus(int n);
int main(void)
{
    int n, digit, test;
    scanf("%d", &n);
    test = plus(n);
    while(test != 0)
    {
        if(test > 9)
            plus(test);
        else
            break;  
    }
    printf("%d", test);
}

int plus(int n)
{
    int digit=0,test=0;
    while(n != 0)
    {
        digit = n%10;
        test = test + digit;
        n = n/10;       
    }
    return test;
}

You are not storing the value returned by plus function in the while body.您没有将plus function 返回的值存储在while主体中。

You can change the condition in while to check whether it is greater than 9 or not, and assign test as test = plus(test);您可以更改while中的条件以检查它是否大于9,并将test分配为test = plus(test);

So, your while will look like this.因此,您的 while 将如下所示。

while(test > 9)
{
    test=plus(test);
}

You need to recursively call the function plus() until the value returned by it becomes less than 10. Like shown below:您需要递归调用 function plus()直到它返回的值小于 10。如下图所示:

int main(void)
 {
    int n=56;
    while(n> 10)
    {
      n = plus(n);
    }
    printf("%d", n);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM