Wednesday, December 30, 2015
C program to round numbers and decimals without using in-built functions
Suppose we want to round off 838.274. Depending on which place value we're rounding to, the final result can vary. For example,
Reference : http://www.calculatorsoup.com/calculators/math/roundingnumbers.php
C Program to round a number to the nearest thousand
C Program to round a number to the nearest hundred
C Program to round a number to the nearest ten
C Program to round a number to the nearest one
C Program to round a number to the nearest tenth
C Program to round a number to the nearest hundredth
- Round to the nearest hundred (838.274) is 800
- Round to the nearest ten (838.274) is 840
- Round to the nearest one (838.274) is 838
- Round to the nearest tenth (838.274) is 838.3
- Round to the nearest hundredth (838.274) is 838.27
Reference : http://www.calculatorsoup.com/calculators/math/roundingnumbers.php
C Program to round a number to the nearest thousand
#include <stdio.h>
int main(void) {
double a=3250;
int x = (a+500)/1000;
x = x*1000;
printf("%d",x); //3000
return 0;
}
C Program to round a number to the nearest hundred
#include <stdio.h>
int main(void) {
double a=3250;
int x = (a+50)/100;
x = x*100;
printf("%d",x); //3300
return 0;
}
C Program to round a number to the nearest ten
#include <stdio.h>
int main(void) {
double a=323.5;
int x = (a+5)/10;
x = x*10;
printf("%d",x); //320
return 0;
}
C Program to round a number to the nearest one
#include <stdio.h>
int main(void) {
double a=838.274;
int x = (a+0.5)*1;
x = x/1;
printf("%d",x); //838
return 0;
}
C Program to round a number to the nearest tenth
#include<stdio.h>
int main(void)
{
float v=838.274;
int c, r, m;
m = v*100; // m = 83827
c = m%10; // c = 7
r = m/10; // r = 8382
if(c>=5)
r++; // r = 8383
v = (float)r/10;
printf("Round to the nearest tenth is %.1f", v); // 838.3
return 0;
}
C Program to round a number to the nearest hundredth
#include<stdio.h>
int main(void)
{
float v=838.274;
int c, r, m;
m = v*1000; // m = 838274
c = m%10; // c = 4
r = m/10; // r = 83827
if(c>=5)
r++;
v = (float)r/100;
printf("Round to the nearest tenth is %.2f", v); // 838.27
return 0;
}
C Program to round a number to the nearest thousand (another method)
#include<stdio.h>
int main()
{
float a=3250.56;
int c = a; // AssigningTruncating decimal part
int i=0,len=0;
int arr[10];
/* Extracting the digits of the number */
while(c!=0){
arr[i]=c%10;
c=c/10;
i++;
}
len=i-1; // Length of the array
/* Rounding to the nearest thousand */
if(arr[2]>=5){
arr[3]++;
}
for(i=0;i<3;i++){
arr[i]=0;
}
//Program outputs: 3000
for(i=len;i>=0;i--){
printf("%d",arr[i]);
}
return(0);
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment