我需要为我的教育编程一个乐透生成器,它将随机滚动数字,并检查重复的条目,否则将替换它们。当我启动程序时,没有任何错误信息,程序也能运行,但我只看到奇怪的字符而不是数字。 问题的图片
我的代码有什么问题?
#include <iostream>
#include <array>
#include <time.h>
std::array<unsigned char, 6> lottoZahlen = {0, 0, 0, 0, 0, 0};
void arrayFuellen();
unsigned char checkDuplikate(unsigned char);
void arraySortieren();
int main()
{
arrayFuellen();
arraySortieren();
std::cout << "\n---- Ihre Glueckszahlen lauten: ----" << std::endl;
for (unsigned char lottoGlueck : lottoZahlen)
{
std::cout << lottoGlueck << std::endl;
}
std::cout << "---- Glueckszahlen Ende ----" << std::endl;
}
void arrayFuellen()
{
srand(time(NULL));
unsigned char wuerfelZahl = 0;
unsigned char wuerfelZahlChecked = 0;
for (unsigned char i = 0; i < sizeof(lottoZahlen); i++)
{
wuerfelZahl = rand() % 45 + 1;
wuerfelZahlChecked = checkDuplikate(wuerfelZahl);
lottoZahlen[i] = wuerfelZahlChecked;
}
}
unsigned char checkDuplikate(unsigned char checkZahl)
{
srand(time(NULL));
bool dublette = false;
do
{
dublette = false;
for (unsigned char j = 0; j < sizeof(lottoZahlen); j++)
{
if (checkZahl == lottoZahlen[j])
{
checkZahl = rand() % 45 + 1;
dublette = true;
}
}
} while (dublette);
return checkZahl;
}
void arraySortieren()
{
unsigned char merker = 0;
bool vertauscht = false;
do
{
vertauscht = false;
for (unsigned char i = 1; i < sizeof(lottoZahlen); i++)
{
if (lottoZahlen[i - 1] > lottoZahlen[i])
{
merker = lottoZahlen[i];
lottoZahlen[i] = lottoZahlen[i - 1];
lottoZahlen[i - 1] = merker;
vertauscht = true;
}
}
} while (vertauscht);
}
有几种方法可以做到你想要的,打印 char
作为整数的十进制值。
用casging int()
:
std::cout << int(lottoGlueck) << "\n";
使用老式的(C式) printf()
,有人会说不要用这个,但用这个有好处也有坏处。printf()
.
printf("%d\n", lottoGlueck);
按照建议,您可以使用 std::to_string()
我个人不建议用这个方法来打印单个字符,只是因为它把一个字符转换为字符串来打印出一个整数。
在生产代码中我使用数字1,在调试中我使用2。这两种方法都有缺点,但你可以阅读一下。这个 来更好地理解这些。
当涉及到将字符串作为十进制值进行ping时,你可以使用 std::to_string()
并 std::cout << std::dec << string << "\n"
.
"char "是一个用于存储字符的类型,输出流将在你的for-loop中如此解释。因此,如果你的值是65,它实际上将被显示为大写字母A(其ASCII值为65)。要显示数字,你应该使用一个输出流能够识别为数字的类型,比如 "int"。
除了问题的答案之外,你还可以通过使用isprint()来检查你的值是否可以打印。
std::cout << isprint(lottoGlueck) << std::endl;
如果你的值是不可打印的,这将打印0(false)。
您打印的是不可打印的字符。https:/upload.wikimedia.orgwikipediacommonsdddASCII-Table.svg。[]之间的字符是不可打印的。
如果你写了: int i = 5
然后 std::cout << i
它将打印相应的字符,值为5。但值5不是字符 "5",所以如果你希望它是一个可打印的数字,你需要转换它。std::cout << std::to_string(i)
(不知道这是否是你的意图:) )