简体   繁体   中英

rand() keeps giving me the same number and decreasing 4 by variable

I was trying to do this work for a class i have but for some reason i can't get the rand() to work, i've tested several diferent things to try and get it to work, but i just can't figure it out. I'm new to C so i might be doing something wrong here please help.

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

int main() {
    srand( time(NULL) );
    int num, rep, nu, ba, bas;
    char B[20] = "";
    char C[20] = "";


    printf("Jogo: Converter Bases!\n");
    printf("\n Quantas perguntas desejas responder? (1-6)");
    scanf("%d", &num);
    while (num <= 0 || num > 6) {
        printf("\n Introduz um  valor valido de 1 a 6: ");
        scanf("%d", &num);
    }
    for (int p=0; p<num; p++) {
        nu=rand()% 10;
        bas=rand()% 3;
        ba=rand()% 3;

        printf("\nnu = %i bas = %i ba = %i", &nu, &bas, &ba);

        while (ba = bas) {
            ba = rand()% 3;
        }
        if (bas = 0) {
            char B[20] = "Octal";
        } else if (bas =1) {
            char B[20] = "Decimal";
        } else {
            char B[20] = "Hexadecimal";
        }
        if (ba = 0) {
            char C[20] = "Octal";
        } else if (ba =1) {
            char C[20] = "Decimal";
        } else {
            char C[20] = "Hexadecimal";
        }
        printf("Converte %i de base %c para base %c\n", &nu, &B, &C);
        scanf("%d", &rep);
    }
    return 0;
}

`

It's because you're writing:

printf("%d", &x);

When you should be writing

printf("%d", x);

In the first case you're printing the memory address of the variable; in the second - the contents of the variable.

The & is required for scanf , because it needs to know the memory address where to put the results, but printf only needs the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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