3

我需要为我的教育编程一个乐透生成器,它将随机滚动数字并检查重复条目并以其他方式替换它们。当我启动程序时,没有错误消息并且程序运行但我只看到奇怪的字符而不是数字。 问题的图片

我的代码有什么问题?

#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);
}
4

4 回答 4

4

"char" 是一种用于存储字符的类型,输出流将在您的 for 循环中将其解释为这样。因此,如果您的值为 65,它实际上将显示为大写字母 A(其 ASCII 值为 65)。要显示数字,您应该使用输出流识别为数字的类型,例如“int”。

于 2020-06-15T13:46:14.660 回答
0

您正在打印不可打印的字符: https ://upload.wikimedia.org/wikipedia/commons/d/dd/ASCII-Table.svg [] 之间的字符不可打印。

如果你写:int i = 5然后std::cout << i

它将打印相应的字符,值为 5。但值 5 不是字符 '5',因此如果您希望它是可打印的数字,则需要对其进行转换: std::cout << std::to_string(i)

(不确定这是否是您的意图:))

于 2020-06-15T13:53:10.817 回答
0

除了您的问题的答案之外,您还可以使用 isprint() 检查您的值是否可打印。

std::cout << isprint(lottoGlueck) << std::endl;

如果您的值不可打印,这将打印 0 (false)。

于 2020-06-15T13:58:53.160 回答
0

有几种方法可以做你想做的事,打印char为整数/十进制值:

  1. 使用套管int()

    std::cout << int(lottoGlueck) << "\n";
    
  2. 使用good old(C风格)printf(),有人会说不要使用这个,但是使用有优点也有缺点printf()

    printf("%d\n", lottoGlueck);
    
  3. 正如建议的那样,您可以使用std::to_string(),我个人不建议将其用于打印单个字符,因为它将字符转换为字符串以打印出整数。

在生产代码中我使用数字 1,在调试中我使用 2。使用两者都有缺点/优点,但您可以阅读本文以更好地理解这些。

当涉及以十进制值 ping 字符串时,您有std::to_string()std::cout << std::dec << string << "\n".

于 2020-06-15T14:28:02.973 回答