1
#include <stdio.h>


int main()
{
   int minutes=0;
   double days=0.0;
   double  years=0.0;
   printf("enter minutes ");
   scanf("%d ",&minutes);
   days= (minutes/60)/24;
   years=days/365;
   printf("no of minutes %d equals no of days are %f , no of years are %f \n",minutes,days,years);

   return 0;
}

During output we have to enter a value two times for program to work, while I used scanf only one time.

Also the value of days is being truncated to integer even though I defined it as double.

alk
  • 69,737
  • 10
  • 105
  • 255
user63555
  • 17
  • 3

2 Answers2

1

Space in a scanf format string matches zero or more white-space characters. But to know where the white-spaces ends the function must be able to read something that is not a white-space character, hence the second input.

Simple solution: Don't use trailing spaces in your scanf format strings:

scanf("%d",&minutes);
//       ^
// Note no space here
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Also value of days is being truncated to integer

Here

  days = (minutes / 60) / 24;

the right side of the assignment is calculated using integer arithmetic, as only integers are involved. Integer arithmetic does not take care of any fractions but just drops them.

For example 1/2 results in 0, or 4/3 results as 1.

So to fix your issue specify the number-literals as floating points like so:

  days = (minutes / 60.) / 24.;

or (more common but in fact the same):

  days = (minutes / 60.0) / 24.0;

or just cast:

  days = ((double) minutes / (double) 60) / (double) 24;

The latter can be simplified to be:

  days = ((double) minutes / 60) / 24;

The latter works, as calculation is done from inner to outer and the arithmetic applied always follows the "Usual Arithmetic Conversions", which in your case is division of double by integer results in a double.

alk
  • 69,737
  • 10
  • 105
  • 255