将int数组更改为char数组

时间:2016-10-10 23:12:50

标签: c++ arrays char int type-conversion

大家好,我在各种情况下运行某些代码时遇到了困难。我有代码可以找到有多少素数,数组中的所有数字,所需的时间,以及打印的素数。这一切都很好,但后来我需要运行相同的代码,但使用char数组。这就是问题所在。这是代码,带有一组int:

#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;

static const int N = 1000;

int main()
{
    int i, a[N];

    clock_t start = clock();

    for (i = 2; i < N; i++) a[i] = i;
    for (i = 2; i < N; i++)
        if (a[i])
            for (int j = i; j*i < N; j++) a[i*j] = 0;

    start = clock() - start;

    int primes = 0;
    for (i = 2; i < N; i++) {
        if (a[i]) {
            primes++;
            cout << " " << i;
            if (primes % 10 == 0)
                cout << "\n";
        }
    }
    printf("\nIt took %d clicks (%f seconds) to find all prime numbers.\n", start, ((float)start) / CLOCKS_PER_SEC);
    cout << "The number of primes out of " << N << " integers is " << primes << endl;
    return 0;
}

当我简单地将'int'替换为数组的“char”,并将'N'设置为10或100之类的东西时,它可以正常工作,除了质数看起来如何。任何更高的东西,没有打印出来。我知道它不是简单地改变它所说的'int'到'char'的地方,但是我对这个主题毫无希望地迷失了。没有帮助我需要再次执行此操作,但更改数组以键入bool(这对我来说也没有多大意义。)

任何形式的洞察力或简单的解决方案都会很精彩。在此期间我会继续寻找一些东西。谢谢!

1 个答案:

答案 0 :(得分:0)

问题是您将i存储到a[i]。当achar数组时,元素的最大值为127(如果char默认为signed)或255(如果unsigned它是256),假设一个典型的系统具有8位字节。如果它已签名,则溢出会导致实现定义的行为;如果它是无符号的,则溢出包围模1

您唯一关心的是元素的值是零还是非零,因此不需要在其中添加不同的值。只需将它们全部初始化为for (i = 2; i < N; i++) a[i] = 1;

services.AddDataProtection()
 .SetApplicationName("Report Book Resource Server")
 .PersistKeysToFileSystem(new DirectoryInfo(folderForKeyStore))
.ProtectKeysWithCertificate(cert);

当您将其更改为布尔值时,这也将起作用。

相关问题