Search code examples
c

printing integers twice in one printf statement in a c program


So the problem I am having is that one of the random number integers is printing twice but only in the second printf statement in the program at the bottom. This code is also just a test for the game Rack-O which I am recreating in c. So if I or someone can figure out how to make this code work the full game will also work. NOTE: if my code looks bad its because I am slightly new to coding.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>


int main(){
    int game = 1;
    srand(time(0));
    const int MIN = 1;
    const int MAX = 60;
    int starting_numbers10 = (rand() % MAX) + MIN;
    int starting_numbers9 = (rand() % MAX) + MIN;
    int sum1;
    int sum2;

    while(game == 1){
        int gamecards = (rand() % MAX) + MIN;
        int start;

        printf("%d\n", gamecards);
        printf("do you want to change numbers 1 or 2 : ");
        scanf("%d", &start);

        if(start == 1){
            sum1 = starting_numbers10 - starting_numbers10 + gamecards;
        }
        else if(start == 2){
            sum2 = starting_numbers9 - starting_numbers9 + gamecards;
        }
        printf("1 new sum: %d\n", sum1);
        printf("2 new sum: %d", sum2); // <-- example of what it prints (523) 52 being its own integer and 3 being the integer that sum1 can become if you select to change sum1

    }
}

I have tried many different combinations of the code over the past few days spending hours at a time trying to fix the problem but I never get the problem solved. Most likely I am just too inexperienced to know what to do but I haven't given up trying. But I expect that it shows the 2 random integers and not 3. I also expect the solution to be simple as well.


Solution

    • sum1 and sum2 isn't being initialized when first used.
      The result when you try to access value of uninitialized variable is Undefined.
      "Behavior is undefined" means anything can legally be happened, like getting weird value, crash of your program or even explosion of your physical machine.
      Initialize them to 0 to make it properly work.
    • printf("2 new sum: %d", sum2); has no newline character at the end of its format string. This would cause output of printf("%d\n", gamecards); to be mixed with it.