【问题标题】:How to convert ASCII value into char in C++?如何在 C++ 中将 ASCII 值转换为 char?
【发布时间】:2013-10-29 09:31:06
【问题描述】:

如何将 5 个随机 ascii 值转换为字符?


提示:

从 97 到 122 随机生成 5 个 ascii 值(所有字母表的 ascii 值)。边走边确定每个ascii值对应的字母,输出5个字母组成的单词。

我的代码:

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main ()
{
srand (time(NULL));
int val1= rand()%122+97;
int val2= rand()%122+97;
int val3= rand()%122+97;
int val4= rand()%122+97;
int val5= rand()%122+97

cout<<val1<<" and "<<val2<<" and "<<val3<<" and "<<val4<<" and "<<val15<<". "<<






return 0;
}

【问题讨论】:

  • 首选&lt;random&gt; 标头。
  • @chris 你什么意思?
  • rand()%122 产生一个范围为 [0, 122) 的值。将 97 添加到这样的值会产生范围 [97, 219) 中的值。不是你想要的。
  • 如果你必须在 3 小时内问 6 个问题,也许你应该多花一点时间研究 proper book

标签: c++ ascii


【解决方案1】:
for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

【讨论】:

    【解决方案2】:

    要将int ASCII 值转换为字符,您还可以使用:

    int asciiValue = 65;
    char character = char(asciiValue);
    cout << character; // output: A
    cout << char(90); // output: Z
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2014-10-10
      • 2017-04-26
      相关资源
      最近更新 更多