【问题标题】:Beginner Here Rand in c初学者在这里 Rand in c
【发布时间】:2014-01-03 06:32:12
【问题描述】:

当谈到 c 时,我是一名一年级学生,需要帮助将 5 个随机值存储在一个数组中并输出它们。这是我在哪里。

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

struct score_card {int A_ones; int B_twos; int C_threes; int D_fours; int E_fives; int  F_sixes; int G_chance;};
int dice_rolls[5];
int randomize(void);

int value;

int main(void) {
struct score_card test;

randomize;
int i;
    for(i = 0; i <= 4; i++){
    printf("%d\n", dice_rolls[i]);
    }
printf("\n");
return 0;
}


int randomize(void){
int i;
srand(time(0));
for(i = 0; i <= 4; i++){
    value = rand() % 6 + 1;
    dice_rolls[i] = value;
  }
}

输出是: 6294304 6294308 6294312 6294316 6294320

目标是使用模除法从 1 -->6 中获取值并将它们存储在 dicerolls 数组中。

【问题讨论】:

  • 你忘了问问题。这不是您预期的输出吗?
  • randomize; --> randomize();
  • 改进代码格式不会有什么坏处。
  • printf("%d", &amp;dice_rolls[i]); --> printf("%d", dice_rolls[i]);
  • int dice_rolls[4]; --> int dice_rolls[5];

标签: arrays random dice


【解决方案1】:

我看到了两个直接的问题。

首先。你没有用换行符终止你的随机数。这就是为什么它们都以大序列串在一起的原因。将输出行更改为:

printf("%d\n", &dice_rolls[i]);

其次,您实际上并没有致电randomize。正确的调用方式是:

randomize();

语句randomize; 只是一个表达式,为您提供函数的地址。在这种情况下,它就像表达式 42; 一样无用,它也什么都不做。但是它是有效的 C,所以编译器不一定会抱怨。

【讨论】:

  • 谢谢!是的 \n 肯定给了我一个 runon 输出。至于随机化我的错误,我正在处理腻子,这有时会让我很难发现我的语法错误。我目前的输出是 6294304 6294308 6294312 6294316 6294320 似乎模块化除法没有给我小于 6 的值。
  • @Fuadk1 你打印的是&amp;dice_rolls[i]dice_rolls[i]地址&amp; 就是这样做的)而不是值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多