Home >Common Problem >How to retain decimals in division in C language
The way to retain decimals in division in c language is to achieve this by setting the type of the value to floating point. When the floating point type is divided by an integer, the result will be expressed in floating point type, or divided by floating point type. The result of a floating point type is still a floating point type, that is, the decimal is retained
[Recommended course: C Language Tutorial 】
For example: the result of 1/2 is different from the result of 1.0/2
Because 1/2 is not defined as a floating point type , so 1/2 is automatically rounded, the result of
is equal to 0
and 1.0/2, since
is expressed in floating point type in advance, the result is obviously: 0.5
Example:
#include <stdio.h> int main() { int a[5],n=2,m=3,k,sum=0; int i=0; printf("请输入被除数n:"); scanf("%d",&n); printf("请输入除数m:"); scanf("%d",&m); k=n%m; sum=n/m; while(i<5) { k*=10; a[i]=k/m; k=k%m; i++; } if(a[4]>=5) a[3]+=1; printf("%d/%d=%d.",n,m,sum); for(i=0;i<4;i++) printf("%d",a[i]); printf("\n"); }
Rendering:
The above is the detailed content of How to retain decimals in division in C language. For more information, please follow other related articles on the PHP Chinese website!