Hi all I need a solution that how to check a number whether it is a decimal or whole number. I had checked this in google but the solutions are in Javascript, Php,Html. I need the solution in c/c++ .
Give an example for more clear -
1400 is a whole number
189.999 is a decimal number likewise
void check(long double n){
if(ceil(n) == floor(n))
print("Whole")
else
print("decimal")
}
The above code snippet fails here.
Best would be, take the input as string. Now check if β.β is present in the string, its a decimal number else its whole number
#include<bits/stdc++.h> using namespace std; int main(){ string s; cin>>s; bool flag=false; for(int i=0;s[i];i++){ if(s[i]=='.'){ flag=true; break; } } if(flag){ cout<<"Decimal number"; } else{ count<<"Whole number"; } }
see the number i have used has a β1β at 6th place after decimal. see the main function
Decimal β¦ but the question he asked was whether the decimal has fraction part equal to 0 or not.
Then best method is input a number as string -
If β.β in string then it will be decimal otherwise whole.
If user consider 2.0 as whole then after β.β there must be only zeroes no other digit.
Take input as a string
if(any element after β.β is greater than one )
decimal
if(any no number after β.β (or) all elements after β.β are zeros)
whole
This Might work:
int main()
{
#define int long long int
long double n;
cin>>n;
if((long double)n==(int)n)cout<<"Whole"<<endl;
else cout<<"Decimal"<<endl;
}
How about this ?
void tell(double n) {
if(n == (int)n)
cout << "whole";
else
cout << "decimal";
}
That will sufficeβ¦
@anon71261517 donβt pass the decimal to any function, just check with these two lines.
Yes,this code is working on the test case you mentioned before.
You can do this
if(n%1==0){
cout << "Whole" <<endl;
}else{
cout << "Decimal" << endl;
}
If the problem is to find if itβs a decimal number, then the best method is to take the input as a string.
If at some point in your implementation you want check if you have an integer or a floating point value, then Iβm sorry but you have to try a different logic. Checking if n == (int) n
or if floor(n) == ceil(n)
will fail when the fractional part is so small, and itβs truncated and stored in the double
as a pseudo integer.
great soln