Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

c - Adding a string as a visual to my code for a function

I've written the following function for a Collatz problem:

int collatz(int n){
    int steps = 0;
    do{
    if (n%2==0){
        n=n/2;
        steps++;
    }
    else{
        n=3*n+1;
        steps++;
    }
    }while(n!=1);
    return steps;
}

I'm trying to add a visual along with the answer. So for example, if n is = to 5. The amount of steps it takes to reach 1 is 5 and that returns which is fine. But I want to add a visual like this 5 -> 16 -> 8 -> 4 -> 2 -> 1. Basically showing the user the process of how we got to 1. I've tried working with a string and an array of strings but I've never really learned much about string manipulation. Any hints or solutions would be really helpful.

question from:https://stackoverflow.com/questions/65907806/adding-a-string-as-a-visual-to-my-code-for-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use printf function to show some string in console. "%d" is number format.

int collatz(int n){
    int steps = 0;

    printf("%d", n);
    do{
    if (n%2==0){
        n=n/2;
        steps++;
    }
    else{
        n=3*n+1;
        steps++;
    }

    printf("->%d", n);
    }while(n!=1);
    printf("
");
    return steps;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...