7

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

  • 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;   
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
tdbr
  • 316
  • 1
  • 3
  • 9
  • 4
    Your question doesn't make sense, as for you to use `scanf`, you must know the type that's being assigned. So, from that logic, you already know the type. Correct me if I am wrong, but I think you question is probably asking to determine if a user entered number (from a string) is an integer or float. – jrd1 Nov 19 '13 at 09:55
  • 1
    If the comments aren't relevant, you can just remove them from the question. – Tom Fenech Nov 19 '13 at 09:56
  • 1
    Yes, but here's the problem. If I use *scanf* i need to declare which type i want. So how to declare the type that im not sure of beacuse it depends on the number that will user put in? – tdbr Nov 19 '13 at 10:01
  • @teddybear What is your actual problem? What makes you think you need to treat floating point and integer differently? If you really do then you'll need two variables. One for floating point and one for integer. – David Heffernan Nov 19 '13 at 10:07
  • float has better precision than int. So if you need to choose a type, choose float. Just make sure the rest of the code is float compatible, so you don't lose the float's precision when needed! – H_squared Nov 19 '13 at 10:11
  • Really, what is the underlying problem? If you would tell us that, then we might be able to give better help. If you keep that from us you are depriving yourself of real help. – David Heffernan Nov 19 '13 at 10:33
  • 3
    Is the problem to determine whether the input has a “floating point” form (has a decimal point or an exponent) or has a non-integer value? “1.0” has floating-point form but is an integer. “1/2” does not have floating-point form but is not an integer. Does the program need to be locale-sensitive (recognize either “,” or “.” as a decimal point depending on user settings)? – Eric Postpischil Nov 19 '13 at 11:29
  • shouldnt the title be renamed to "how to check if string represents integer or float?" ? – Rookie Nov 19 '13 at 11:40
  • 1
    @EricPostpischil yes, that's it – tdbr Nov 19 '13 at 11:55
  • 1
    @teddybear: Which? The first question is not yes-no, it is either-or: Is the problem to check the **form** of the input or the **value**? And there is a second question, which is yes-no: Does the program need to be locale sensitive? – Eric Postpischil Nov 19 '13 at 12:12
  • Since the question is on hold, I will have to answer in the comments: How about get the number as a `float` and as `int`. Then subtract `float version` from `int version` (int must be cast to float). If the result is `0`, then the number is an integer, else it is a float. – H_squared Nov 19 '13 at 16:02
  • Also, It is possible to get the `float version`, lets call it myfloat, then `if (ceilf(myfloat)==myfloat){printf("myfloat is an integer\n");}` – H_squared Nov 19 '13 at 16:10
  • that was a time ago, I think that @hhachem answer is correct. Rest of responses are much to high-leveled i think. That's a first degree of studies :D – tdbr Mar 11 '14 at 14:57

4 Answers4

18

I would suggest the following:

  1. Read the number into a floating point variable, val, say.
  2. Put the integer part of val into an int variable, truncated, say.
  3. Check whether or not val and truncated are equal.

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 val is outside the range of values that can be stored in an 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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    but what if the input is 123.0? – perreal Nov 19 '13 at 10:02
  • @perreal That is an integer is it not? – David Heffernan Nov 19 '13 at 10:05
  • 1
    In C, it is a float :) I see your point though. – perreal Nov 19 '13 at 10:06
  • @perreal Well, in C it is `double`, but in mathematics it is an integer. That's how I interpreted the question anyway. – David Heffernan Nov 19 '13 at 10:07
  • 1
    Well no, `123.0` is clearly not an integer, there is a decimal point and a decimal fraction. I suppose you might want to claim that it is within some tolerance of an integer. – High Performance Mark Nov 19 '13 at 10:14
  • 1
    @HighPerformanceMark In the realm of mathematics, I am reasonably confident that `123.0` is an integer. Your comment on tolerance makes me chuckle. – David Heffernan Nov 19 '13 at 10:15
  • 3
    Careful gents, we are still discussing *computers*, not *mathematics*. Not every possible integer can be stored in an `int` integer -- or, for that matter, in a `float` or `double`. The OP might want to clarify what he means with 'integer'. (Also, `123.0` is a perfectly reasonable representation for `123.00000001` ;) – Jongware Nov 19 '13 at 10:51
  • @Jongware You can discuss whatever you like. Since the question asker is deeply confused, the question is open to interpretation. I respect your interpretation, but I don't see how you state clearly what we are discussing. In fact on the one hand you state that we are not discussing maths, and then in the next breath you say that the question needs to be clarified. I agree. The question is vague. Hence my final paragraph describing my assumptions. – David Heffernan Nov 19 '13 at 10:55
9

Keep it simple:

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

  2. Use sscanf to 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.3 won'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
    }
    
user694733
  • 15,208
  • 2
  • 42
  • 68
  • well, it's not my level yet i think so, maybe a easier solution. – tdbr Nov 19 '13 at 18:11
  • 1
    I think it would be better to put a space before the `%n` to allow it to skip trailing space. You can then check whether the character at the end is a null byte — if so, there was (possibly empty) leading white space, a number, and (possibly empty) trailing white space. I'd use the `%n` in both tests. – Jonathan Leffler Jul 02 '17 at 23:13
0
#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;
}
perreal
  • 94,503
  • 21
  • 155
  • 181
0

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 ]!='\0'; 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
}
Ray
  • 568
  • 6
  • 20
  • what is checkFunction()? – condorwasabi Nov 19 '13 at 10:12
  • It should be checkType. I forgot to change the function name. – Ray Nov 19 '13 at 14:50
  • 1
    But checkType() returns IS_INT (that is 2) if the number is integer or IS_FLOAT (that is 1) if it's a float. In your main the test in the if clause is wrong, because you check if the value returned by checkType() is true (not 0) or false (0). So the printf("undifined"); will never be executed. The "if" and the "else if" have the same test condition and it's an error too because those conditions should always be disjoint. – condorwasabi Nov 19 '13 at 17:11
  • @condorwasabi you are right. Pardon that I was writing too fast. – Ray Nov 23 '13 at 08:49