6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語で小数点以下を四捨五入する関数を実装

Last updated at Posted at 2014-09-29

#include <stdio.h>

//切り上げ
int roundUp(double n){
	if(n >= 0){ 
		return (int)n + 1;
	}else{
		return (int)n - 1;
	}
}

//切り捨て
int roundDown(double n){
	return (int)n;
}

//四捨五入
int roundOff(double n){
	double decimal = 0;

	decimal = n - (int)n;

	if(decimal >= 0.5 || decimal <= -0.5){
		return roundUp(n);
	}else{
		return roundDown(n);
	}
}


int main(){
	
	double n;
	int ans = 0;

	printf("小数点以下で四捨五入を行う\n");
	printf("実数を入力:"); scanf("%lf",&n);

	ans = roundOff(n);

	printf("%d\n",ans);

	return 0;
}

もっと簡単にやる方法がありました。



#include <stdio.h>

int main(){	
    double real;
    double ans;

    printf("実数を入力:"); scanf("%lf",&real);

	//四捨五入
    if(real >= 0){
    	ans = (int)(real + 0.5);
    }else{
    	ans = (int)(real - 0.5);
    }

    printf("%fを四捨五入 結果[%f]\n",real,ans);

    return 0;
}

6
8
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?