0

I am writing a simple program to round numbers. It works fine when I enter something like 1.4 (gives me 1.0) or 2.6 (gives me 3.0). But when I enter 1.45, it should give me 1.5 but it prints 1.0. Or for 2.85 (should be 2.9, it prints 3.0). How do I make this work? I cannot use any functions.

#include<stdio.h>
const float add = 0.5;
int main(void)
{
      float v;

       printf("Please enter a value to be rounded: ");
       scanf("%f", &v);

       v = v + add;
       v = (int)v;

       printf("The rounded value is %.2f", v);

      return 0;
}
pdhimal1
  • 229
  • 4
  • 9
  • 19

6 Answers6

2

Try this code. You need to break your floating value into Modulus and Dividend.

#include<stdio.h>
int main(void)
{
  float v;
  int con, r_value, mul;
  printf("Please enter a value to be rounded: ");
  scanf("%f", &v);
  mul=v*10;
  con=mul%10;
  r_value=mul/10;
  if(con>=5)
  r_value=r_value+1;
  else 
  r_value=r_value;
  printf("The rounded value is %.2d", r_value);

  return 0;
}

Above code is modified to be used for Negative Numbers also.

float v;
int con, r_value, mul;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
mul=v*10;
con=mul%10;
r_value=mul/10;
if(v>0)
{
  if(con>=5)
    r_value=r_value+1;
  else 
  r_value=r_value;
}

  else if (v<0)
    {
        if(con<=-5)
        r_value=r_value-1;
        else 
        r_value=r_value;
    }
          printf("The rounded value is %.2d", r_value);  
Fahad Naeem
  • 515
  • 7
  • 15
0

Int value simply removes the value after decimal point it does't round of to nearest number

In your case when you give 2.45

2.45 + 0.5 = 2.95

which is rounded off to 2(2.0 since your asking for precision) i.e the decimal part is truncated not rounded off.

KARTHIK BHAT
  • 1,410
  • 13
  • 23
0

Ints do not have decimal places, so a cast from float to int then back to float will leave only the integer value.

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
0

Your subject (rounding to the second decimal place) does not match your question (rounding to an arbitrary position based on the input). That makes it difficult to answer your question properly.

That said, your code

 v = v + 0.5;
 v = (int)v;

will round a number to the nearest integer. I'm not sure why you expect the int cast to do anything else.

hymie
  • 1,982
  • 1
  • 13
  • 18
0

You can do:

printf("%.2f", ((int)(v * 100 + 0.5) / 100.0));
Peter Bratton
  • 6,302
  • 6
  • 39
  • 61
0

You are using v = (int)v;, how can it give 1.5 for input of 1.45.

To get what you want, you can just print the decimal digits 1 less than in original, i.e. Suppose you have 2.455 which has 3 decimal digits, you can just print that number using %.2f and it will automatically be rounded off.

0xF1
  • 6,046
  • 2
  • 27
  • 50