Exercise 30
Write a program which reads float value developed as decimal extension and
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;
}
Check if float is integer: is_integer() float has is_integer() method that returns True if the value is an integer, and False otherwise. For example, a function that returns True for an integer number ( int or integer float ) can be defined as follows. This function returns False for str .
Check if the value has a type of number and is not an integer. Check if the value is not NaN . If a value is a number, is not NaN and is not an integer, then it's a float.
int x; if (int. TryParse(inputString, out x)) { // input is an integer. }
The C library function int isdigit(int c) checks if the passed character is a decimal digit character. Decimal digits are (numbers) − 0 1 2 3 4 5 6 7 8 9.
I would suggest the following:
val
, say.val
into an int variable, truncated
, say.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.
Keep it simple:
Read input as a string to a buffer fgets(buffer, BUFFER_SIZE, stdin);
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
.
If previous step failed, try reading floating point:
double dbl;
r = sscanf(buffer, "%lf", &dbl);
if(r == 1) {
// is double
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With