Home > Common Problem > body text

How to retain decimals in division in C language

清浅
Release: 2022-01-12 15:40:25
Original
75151 people have browsed it

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

How to retain decimals in division in C language

[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");   
}
Copy after login

Rendering:

How to retain decimals in division in C language

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template