c - 为什么我的程序返回相同的字符?

标签 c output

这是一个程序,用于检查输入数字是否为两个质数 ('Y') 或非 ('N') 的乘积。

 #include <stdio.h>


// the function checks if the number is prime
int is_prime(int z) {
    int i;
    for(i=2; i<z; i++){
        if(z%i == 0){
            return 0;
    }
    return 1;
  }
}

/* the function checks if the given number is a
product of two prime numbers bigger than 2*/
int is_prime_product(int x) {
    int j;

    for(j=2; j<x; j++){
        if(x%j == 0){
            if(is_prime(x/j) && is_prime(j)){
                return 1;
                break;
            }else return 0;
        }
    }
 }

    int main() {
        int n=0;
        int c;

        do{
        c=getchar();
        if((c>='0') && (c<='9')){
            n= n*10+(c-'0');
        }
    } while (('0'<=c) && (c<='9'));


    if(is_prime_product(c)){
        putchar('Y');
    }else{
        putchar('N');
    }

        return 0;
}

我不知道为什么这个程序总是返回“Y”,即使它应该返回“N”。我只是不明白错误在哪里。

最佳答案

部分答案:is_prime 的更好版本:

int is_prime(int z) 
{
    if(z <= 1) return 0;
    if(z == 2) return 1;
    int i;
    for(i=3; i<sqrt(z); i+=2)
    {
        if(z%i == 0) return 0;
    }
    return 1;
 }

在 2 的测试之后,测试奇数因子直到测试数的平方根就足够了。 (还修复了花括号)

错误原因:

if(is_prime_product(n)) ...

测试输入数字n不是最后一个字符c


编辑

关于更好(更具可读性、更可靠等)代码的一些提示:

  • 使用与问题匹配的类型(bool 而不是 int)
  • 使用好的变量名(i 仅用于循环,z 仅用于 float )
  • 使用有意义的变量名(数字而不是 n)
  • 一致的大括号,运算符周围的间距

这些东西很重要!

看看:

bool is_prime(unsigned int number) 
{
    if(number <= 1) return false;
    if(number == 2) return true;

    for(unsigned int factor = 3; factor < sqrt(number); factor += 2)
    {
        if(number % factor == 0) return false;
    }
    return true;
 }

关于c - 为什么我的程序返回相同的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469409/

相关文章:

c++ - bool 乘法

c++从文件中读取并输出排序的内容

python - Linux python 从正在运行的 python 脚本读取输出

python - 设置 ipython 的默认科学记数法阈值

c - 分配负值时无符号变量的意外行为

c - EasyHook:在 native C 应用程序中从 32 位应用程序注入(inject) 64 位 dll?

c - arm-linux-gcc 编译器链接,找不到文件

c - 仔细检查缓冲区的大小

iphone - 使用 AppDelegate 使变量对整个应用程序可用

r - 将回归结果输出到 R 中的数据框中