2

I want to make simple program with X and N type double so if a user enter a number that is 4.4 then do-while loop gets out and prints bla bla.
And if user enters a number that is 5.6 then do-while needs to get back and make user to enter a number that is lesser than n.5
Is it even possible to make condition with type double?

#include <stdio.h>

int main(){
double x=0.0,n=0.0;

    do{
         printf("Enter n(so it's less than n.5):");
         scanf("%lf",&n);
         x = n - (int)n;

     }while(n<=0.0 && x>=0.5);

     printf("Integer part is %d\nDecimal is %.3lf\n",(int)n,x);
     return 0;
}
komad1na
  • 53
  • 8
  • Did you try the code? Did you encounter any problems? – wmk Oct 22 '15 at 19:19
  • Yes, why is he go out from do-while when i type **2.6** and even when I type -9.7 he goes out and print Int part is -9 and Decimal is 0.6? – komad1na Oct 22 '15 at 19:20

4 Answers4

3

Yes, it's absolutely possible. However, you wrote a condition that can never be true.

while(n<=0.0 && x>=0.5)

Can you tell me a number that's less than or equal to zero and also more than or equal to 0.5? There's no such thing.

An invalid number in your case is a number that's less than or equal to zero, or a number that's more than or equal to 0.5, so you need to change the && to ||.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • MY GOD AT FIRST I TYPED **||** and it was going out then i changed to **&&** and still had problem. Tnx man :) – komad1na Oct 22 '15 at 19:23
  • 2
    The condition tests `n` and `x`, your second para suggests you read it as testing `n` and `n` . (It can still never be true , but for slightly different reason) – M.M Oct 22 '15 at 19:51
2

Is it even possible to make condition with type double?

Yes. It sure is.

The relational operators <= and >= work fine with floating point types.

The one main difference between using them for integral types and floating point types is that you have to deal with the imprecise nature of floating point representations. See Floating point comparison as a starting point for the problems you have to deal with when comparing floating point numbers.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

I think you meant

while(n<=0 || n>5)
dko
  • 698
  • 1
  • 6
  • 18
0

The problem will occurs with n<=0.0 it works only with nagative or zero double values and x>=0.5 the positive number. This code can help you with this issue.

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

int main(){
double x=0.0,n=0.0;

    do{
         printf("Enter n(so it's less than n.5):");
         scanf("%lf",&n);
         x = n - (int)n;

     }while(fabs(x)>=0.5);

     printf("Integer part is %d\nDecimal is %.3lf\n",(int)n,x);
     return 0;
}
Mykola
  • 3,343
  • 6
  • 23
  • 39