首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

随机字符 随机数 和 int转换char 有关问题

2012-03-04 
随机字符 随机数 和 int转换char 问题程序目的:产生两个随机字符我的期望过程: 随机生成两个随机数。 根据A

随机字符 随机数 和 int转换char 问题

程序目的:产生两个随机字符
我的期望过程: 随机生成两个随机数。 根据ASCII 码 把 随机数转换成 字符型

结果:随机数不同。 但是转换成 字符型之后 却变得一样

求解


C/C++ code
#include <iostream>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <stdio.h>#include <time.h>using namespace std;// A~Z    65~90// a~z    97~122int main(){    srand (time(NULL));    char * pwd;    pwd = crypt("test", "ab");               //char *crypt(const char *key, const char *salt);                        // char * salt is a-z A-Z 0-9 ./                        // char * key is user typed in password    cout <<"after crypt()= "<< pwd << endl;    char word_1;    char word_2;    int num_1;    int num_2;        word_1 = (rand()%26)+'a';// always generate same value    word_2 = (rand()%26)+'a';// 这里两个随机字符 总是相同        num_1 = rand()%122+65;    num_2 = rand()%122+65;    while (word_1==word_2)// got different value   这里解决了随机数总是相同的问题    {        word_2 = (rand()%26)+'a';    }        word_1 = num_1;// 根据 ASCII 转换成char型 期望得 word_1 和 word_2 得到不同的字符    word_2 = num_2;// 随机数不同了 但是这里得到的两个 char 字符 却又相同了        cout << "random word_1= " << word_1 << endl;    cout << "random word_2= " << word_1 << endl;    cout << "random num_1= " << num_1 << endl;    cout << "random num_2= " << num_2 << endl;    cout << "int to char word_1= " << word_1 << endl;      cout << "int to char word_2= " << word_1 << endl;    return 0;}





[解决办法]
不需要这么麻烦!
C/C++ code
/*- * Copyright (C) * * $Id$ * * $Log$ */#ifndef lintstatic const char rcsid[] = "$Id$";static const char relid[] = "$""Date: "__DATE__" "__TIME__" "__FILE__" $";#endif /* not lint *//** * @file             * @brief            */#include <stdio.h>#include <stdlib.h>#include <time.h>const char charset[] =    "0123456789"    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"    "abcdefghijklmnopqrstuvwxyz";int randchar(void){    return charset[rand() % (sizeof(charset) - 1)];}intmain(int argc, char *argv[]){    int i;    srand(time(0));    for (i = 0; i < 72; i++)        putchar(randchar());    putchar('\n');    return 0;} 

热点排行