简体   繁体   English

rand()不断给我相同的数字,并按变量递减4

[英]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. 我试图在我上过的课上做这项工作,但由于某种原因我无法让rand()工作,我已经测试了好几种不同的方法来尝试使其工作,但我只是想不通出来。 I'm new to C so i might be doing something wrong here please help. 我是C的新手,所以我在这里做错了,请帮忙。

#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. scanf需要& ,因为它需要知道将结果放在哪里的内存地址,但是printf只需要该值。

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

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