收集数字并打印出来

标签 c random string-concatenation

我想要完成的是生成 100 个随机的 0 和 1,将它们全部添加到一个变量中,然后打印出来。我现在拥有的东西我不知道如何工作。如果有人能解释我做错了什么,我将不胜感激。

randstring (void){
    int i;
    int num;
    char buffer[101];
    i=100;
    while(i>0, i--){
        num = rand()%2;
        strcpy(buffer, num);
    }
    return(buffer);
}

我现在拥有的是:

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

main (void){
    printf("%f", randstring());
}
randstring (void){
    int num;
    char buffer[101];
    int i = 100;
    while(i-- >= 0) buffer[i] = rand() % 2;
    return(buffer);
}

最佳答案

buffer[i] = (rand() % 2) 怎么样? '1' : '0'; 在循环体中?

我会做 buffer[100] = 0;

但更糟糕的问题是你不能返回缓冲区,因为一旦你的函数退出,它就会被覆盖。它被分配在栈上,当函数退出时栈被重用。您需要执行 malloc 和 free,或者将缓冲区及其长度传递给此函数。

这给了我们:

#include <stdio.h>

#define RAND_LENGTH 100

char *randstring (char *buffer, int length);

int main (int a, char **b){
    char buffer[RAND_LENGTH + 1];
    printf("%s", randstring(buffer, RAND_LENGTH));
}

char *randstring (char *buffer, int length){
    int i = length;
    while(--i >= 0) {
        buffer[i] = (rand() % 2) ? '1' : '0';
    }
    buffer[length] = 0;
    return buffer;
}

关于收集数字并打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/968753/

相关文章:

c - 让编译器找到 Cmake 创建的文件

c - 获取基本文件权限以与 C 中的输入进行比较

java - 如何做RandomBug代码

java - Java 9 中的字符串连接是如何实现的?

c - 如何用另一个函数覆盖一个函数?

c - C 中的段错误

python - 如何从字典中获取随机值?

java - 随机选择的字符串

jQuery append() 不适用于连接字符串

string - 如何在 Swift 中连接字符串?