在C语言中,如何将一个浮点数变换成整数?

Python026

在C语言中,如何将一个浮点数变换成整数?,第1张

需要准备的材料分别有:电脑、C语言编译器

1、首先,打开C语言编译器,新建一个初始.cpp文件,例如:test.cpp。

2、在test.cpp文件中,输入C语言代码:double a = 2.71828printf("%d", int(a))。

3、编译器运行test.cpp文件,此时成功将浮点数2.71828转换为了整数2。

字符串转整数可以有两种方法:

1.使用c语言自带的库函数:atoi。

函数原型:int atoi(const char *nptr)

功能:把字符串转成整型数。

例如:

#include <stdlib.h>

#include <stdio.h> 

int main(void)

{

    int n

    char *str = "12345"

    n = atoi(str)

    printf("int=%d\n",n)

    return 0

}

/*

输出:

int = 12345

*/

2.可以自己编写一个转换函数:

#include <stdio.h>

#include <stdlib.h>

int atoi(char *s)

{

int t=0

while(*s){

t=t*10+*s-'0'

s++

}

return(t)

}

int main ()

{

char a[]="12345"

int n = atoi(a)

printf("n=%d ",n)

return 0

}

/*

输出:

n = 12345

*/