Sum and Difference of Two Numbers - Hacker Rank Solution
- The problem statement mentions how to input variables of a particular data type and also how to output variables.
- We need to declare two variables of type int (
%d
) and two of type float (%f
). - Input the variables using the scanf function and print the output using the printf function.
- The tricky part here is to format the output of the floats such that the variable is rounded to one decimal place. This can be done like this:
printf("%.1f", a)
. Here the.1
in the format specifier, specifies that the variable should be rounded down to 1 decimal place.
Problem Setter's code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int n, m;
float a, b;
scanf("%d %d", &n, &m);
scanf("%f %f", &a, &b);
int sum_of_ints = n + m;
float sum_of_floats = a + b;
int diff_of_ints = n - m;
float diff_of_floats = a - b;
printf("%d %d\n", sum_of_ints, diff_of_ints);
printf("%.1f %.1f", sum_of_floats, diff_of_floats);
return 0;
}
Sum and Difference of Two Numbers – Hacker Rank Solution
ReplyDeletehttps://www.codeworld19.com/sum-and-difference-of-two-numbers-hacker-rank-solution/