简体   繁体   English

如何编写确定输入是素数还是数值的C程序

[英]How to write a C program that determines if input is prime and numeric

I'm trying to write a programme with C that asks for a number to be input and then determines whether or not it is a prime number. 我正在尝试用C编写一个程序,要求输入数字,然后确定它是否是质数。 If the input is a non-numeric character or string, it outputs the message INVALID INPUT. 如果输入是非数字字符或字符串,则输出消息INVALID INPUT。 I have managed to create code that can determine if a number is prime and also if it is non-numeric but when I try and combine them, it doesn't work. 我设法创建了可以确定数字是否为质数以及是否为非数字的代码,但是当我尝试将它们组合时,它将无法正常工作。 Eg if I input a non-numeric value it will output the correct message but when I input a numeric value, nothing happens and I'm not sure why. 例如,如果我输入非数字值,它将输出正确的消息,但是当我输入数字值时,什么也没有发生,并且我不确定为什么。 Can anybody help? 有人可以帮忙吗?

#include <stdio.h>
#include <string.h>
#define FALSE 0
#define TRUE 1

int numeric( char *string )
{
    int i, valid;
    valid = TRUE;

    if (string[i] < '0' || string[i] >'9')
        valid = FALSE;
    return valid;
}

void main()
{
    char number[5];
    printf("Please enter a decimal number>");
    gets( number );

    if (numeric(number) == TRUE)
    {
        int n, i, a = 0;
        scanf_s("%d", &n);

        for (i = 2; i <= n / 2; ++i)
        {
            if (n%i == 0)
            {
                a = 1;
                break;
            }
        }

        if (n == 1)
        {
            printf("1 isn't a prime number.");
        }
        else
        {
            if (a == 0)
                printf("number entered is a prime number");
            else
                printf("number entered is not a prime number");
        }
    }
    else 
        printf("INVALID INPUT \n"); 
} 

In addition to the bug mentioned in @Michail's comment (failing to initialise i to zero in numeric : 除了@Michail的注释中提到的错误(未能将i初始化为numeric零):

Your problem is that in the truthy branch of if (numeric(number)) , you call scanf_s , which will try to read new input from STDIN . 您的问题是,在if (numeric(number))的真理分支中,您调用scanf_s ,它将尝试从STDIN读取新输入。 You've already read the number from STDIN in your call to gets . 您已经阅读次数STDIN在调用gets The behaviour you observe ("nothing happens") is to be expected: your program is waiting for you to enter more input. 您观察到的行为(“什么也没有发生”)是可以预期的:您的程序正在等待您输入更多输入。

You leave yourself open to buffer overflow but that's a separate issue. 您可以随时进行缓冲区溢出,但这是一个单独的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM