如何在c中保留小数
我正在编写简单的家庭作业代码。 当我用它定义时,我从用户获得一个数字,即3.4
scanf("%d",&a)
它只需3个就可以这样做。 我定义a
as
int a;
我该怎么办?
使用浮动
float a; scanf("%f", &a);
我认为你对c编程很新。 这是一项非常简单的工作。 这可以这样做: –
float a; // to input a data in the variable a scanf("%f",&a); //to display the stored data printf("%f\n",a); //or printf("%.nf\n",a);//specify value of n //maximum value of n is 6 also is its default value //for eg printf("%.2f",a); will display decimal number upto two digits after the decimal place //you can know more about displaying data as %d: decimal value (int) %c: character (char) %s: string (const char *) %u: unsigned decimal value (unsigned int) %ld: long int (long) %f: float value (float or double) %x: decimal value in Hexadecimal format %o: decimal value in octal format
有关avialabe格式规范列表,请转到此处
%d用于int。 3.4不是int类型,可以使用float。
float x; scanf("%f", &x);
有关数据类型的详细信息,请访问以下url : http : //en.wikipedia.org/wiki/C_data_types
还有: http : //www.techonthenet.com/c_language/variables/index.php
你应该定义a
as
float a;
并在scanf
中用%f
替换%d
scanf("%f", &a);
我该怎么办?
读取C中格式化输入/输出的基础知识 。
它对于int变量非常简单,我们使用%d格式说明符,如果我们想要float,我们使用%f格式说明符。 因为根据IEEE int和float位图格式不同。
你声明int a只能取整数值所以你需要做的是使它浮动,用于具有小数点的数字
漂浮一个; 的scanf(%F,A);