C语言 C - 如何检查数字是整数还是浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20068234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:20:59  来源:igfitidea点击:

C - How to check if the number is integer or float?

cfloating-pointinteger

提问by tdbr

Exercise 30
Write a program which reads float value developed as decimal extension and

练习 30
编写一个程序,读取作为十进制扩展开发的浮点值和

  • If it's integer, it says that it's integer
  • on the other hand it rounds it to integer and writes the result.
  • 如果是整数,则表示它是整数
  • 另一方面,它将其舍入为整数并写入结果。

Remember about data control

记住数据控制

Here's the new one without this message about integer type.

这是新的,没有关于整数类型的消息。

#include <stdio.h>
#include <math.h>

int main(){
    double x;              //the argument of f(x)
    printf("Program demands x");
    printf("\nand writes the rounded value\n");
    printf("Author: xXx\n\n");
                          //loading data
    printf("Write x in float type in decimal extension  "); // after many tries, program is not rounding the value
    if (scanf("%lf",&x)!=1 || getchar()!='\n'){
        printf("Wrong data.\n");
        printf("\nEnd of program.\n");
        return 0;     
    }
    double round( double x );
    printf( "Rounded value is = %lf\n", x);
    printf("\nEnd of program.\n");
    return 0;   
}

回答by user694733

Keep it simple:

把事情简单化:

  1. Read input as a string to a buffer fgets(buffer, BUFFER_SIZE, stdin);

  2. Use sscanfto try reading integer:

    int i, r, n;
    r = sscanf(buffer, "%d%n", &i, &n);
    if(r == 1 && n == strlen(buffer)) {
        // is integer
    }
    

    Extra length check here is to make sure that all characters are evaluated, and number like 12.3won't be accepted as 12.

  3. If previous step failed, try reading floating point:

    double dbl;
    r = sscanf(buffer, "%lf", &dbl);
    if(r == 1) {
            // is double
    }
    
  1. 将输入作为字符串读取到缓冲区 fgets(buffer, BUFFER_SIZE, stdin);

  2. 使用sscanf尝试读取整数:

    int i, r, n;
    r = sscanf(buffer, "%d%n", &i, &n);
    if(r == 1 && n == strlen(buffer)) {
        // is integer
    }
    

    此处的额外长度检查是为了确保对所有字符进行评估,并且12.3不会接受类似数字的12.

  3. 如果上一步失败,请尝试读取浮点数:

    double dbl;
    r = sscanf(buffer, "%lf", &dbl);
    if(r == 1) {
            // is double
    }
    

回答by David Heffernan

I would suggest the following:

我建议如下:

  1. Read the number into a floating point variable, val, say.
  2. Put the integer part of valinto an int variable, truncated, say.
  3. Check whether or not valand truncatedare equal.
  1. 将数字读入浮点变量val,例如。
  2. 将 的整数部分val放入一个 int 变量中truncated,例如。
  3. 检查valtruncated是否相等。

The function might look like this:

该函数可能如下所示:

bool isInteger(double val)
{
    int truncated = (int)val;
    return (val == truncated);
}

You will likely want to add some sanity checking in case valis outside the range of values that can be stored in an int.

您可能需要添加一些完整性检查,以防val超出可以存储在int.

Note that I am assuming that you want to use a mathematician's definition for an integer. For example, this code would regard "0.0"as specifying an integer.

请注意,我假设您想使用数学家对整数的定义。例如,此代码将"0.0"视为指定整数。

回答by perreal

#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
    char buffer[128], *p = buffer; 
    int   isint;
    fgets(buffer, sizeof buffer, stdin);
    if (p[0] == '+' || p[0] == '-')
      p++;
    isint = strlen(p) - 1;
    for (; *p && *p != '\n' && isint; p++) {
        isint = isdigit(*p);
    }   
    if (isint)
        printf("Woaaa\n");
    return 0;
}

And slightly cleaner version based on comparing the input string and the string created using the scanned integer:

基于比较输入字符串和使用扫描的整数创建的字符串的稍微干净的版本:

#include <stdio.h>
#include <string.h>
int main() {
    char buffer[128], tostr[128];
    int d;
    fgets(buffer, sizeof buffer, stdin);
    buffer[strlen(buffer) - 1 ] = 0;
    sscanf(buffer, "%d", &d);
    sprintf(tostr, "%d", d); 
    if (!strcmp(buffer, tostr)) {
        printf("Woa\n");
    }
    return 0;
}

回答by Ray

I would suggest that you can get the input by string and check whether it is float or integer.

我建议您可以通过字符串获取输入并检查它是浮点数还是整数。

for example:

例如:

#define IS_FLOAT = 1;
#define IS_INT = 2;
int main()
{
    char tempString[20];

    scanf("%s", tempString);

    if(checkType(tempString)==IS_INT)
        printf("This is integer\n");    
    else if(checkType(tempString)==IS_FLOAT)
        printf("This is Float");
    else
        printf("undifined");
}

int checkType(char *input)
{
    short int isInt=0;//we use int as a boolean value;
    short int isFloat=0;
    short int isUndifined=0;
    int count;

    for(count = 0 ; input[count ]!='##代码##'; count++)
    {
        if(isdigit(input[count]))//you should include ctype.h at the beginning of this program
            isInt=1;
        else if(input[count] == '.')
            isFloat=1;
        else
            return -1;//some character that neither int nor '.' char.
    }
    if(isInt == 1 && isFloat ==1)
        return IS_FLOAT;
    else if(isInt == 1 && isFloat ==0)
        return IS_INT;
    else
        return -1;//illegal format
}