【问题标题】:There is one error in each of the following projects ( I need to fix them )以下每个项目都有一个错误(我需要修复它们)
【发布时间】:2025-12-15 02:05:01
【问题描述】:

以下每个项目都有一个错误(我需要修复它们)。在第一个项目中,代码不适用于较大的 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;
}

【问题讨论】:

  • 如果条件都不成立,toDecimal 会返回什么?

标签: c debugging hex codeblocks primes


【解决方案1】:

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

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

另外请学习如何使用调试器。这实际上花了 5 秒的时间来计算,足够设置断点并执行几次。

【讨论】:

    最近更新 更多