以下项目各有一个错误(需要修改)

There is one error in each of the following projects ( I need to fix them )

以下项目各有一个错误(需要修改)。在第一个项目中,代码不适用于较大的 n 值,而在第二个项目中,我不知道为什么程序无法正常工作。 toDecimal 函数工作正常,问题是如果我想要读取一个 1 位数字,程序将停止并且 10 将显示在屏幕上:s。我正在寻求一些帮助和优化,感谢您的宝贵时间。

//prints the number of primes <= n < 10^5
#include <stdio.h>

int primes[100000];
int main(void)
{
    int n, nrp = 0;
    scanf("%d",&n);
    for(int p=2; p<=n; p++)
    {
        if (primes[p]==0)
        {
            nrp++;
            for(int x=p*p; x<=n; x+=p)
                primes[x] = 1;
        }
    }
    printf("number of primes: %d", nrp);
    return 0;
}



//converts a hexadecimal number with k<=10 digits to decimal
#include <stdio.h>

int toDecimal(char c)
{
    if ( 'a' <= c && c <= 'f' )
        return c-'a'+10;
    if ( 'A' <= c && c <= 'F' )
        return c-'A'+10;
    if ( '0' <= c && c <= '9' )
        return c-'0';
}

int main(void)
{
    char c='x';
    int k = 0;
    long long nr = 0;
    printf("Number of digits: ");
    scanf("%d",&k);
    for(int i=0; i<k; i++)
    {
        scanf("%c",&c);
        nr = 16*nr + toDecimal(c);
    }
    printf("\n%lld\n", nr);
    return 0;
}

在第一个程序中,当p足够大时,int x = p*p;会溢出。

在第二个中,您的 scanf 正在读取一个换行符 (c = 10) 并且您的 toDecimal 函数没有对无效字符的保护,因此它返回垃圾数据。无论位数多少,每个输入的结果都是错误的。使用 scanf(" %c",&c); 代替(注意空白)将修复它。这将使它忽略实际字符之前的任何内容。无论哪种方式,您都需要对代码进行一些重大更改以检查无效输入,而且如果您输入足够大的数字,则不会检查 nr 是否可能溢出。

另请学习如何使用调试器。这实际上花了 5 秒来弄清楚,足够的时间来设置断点和步进几次。