【发布时间】:2013-09-29 13:51:03
【问题描述】:
我正在为家庭作业编写简单的代码。 当我用
定义它时,我从用户那里得到一个数字,即 3.4scanf("%d",&a)
这样做只需要 3 次。我将a 定义为
int a;
我该怎么办?
【问题讨论】:
我正在为家庭作业编写简单的代码。 当我用
定义它时,我从用户那里得到一个数字,即 3.4scanf("%d",&a)
这样做只需要 3 次。我将a 定义为
int 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 e.g. 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 列表,请转到here
【讨论】:
n 在%.nlf 中的最大值是多少,例如。 long float 或 double?
使用浮动
float a;
scanf("%f", &a);
【讨论】:
a中的3.4,只是一个近似值。
%d 用于 int。 3.4不是int类型,可以用float。
float x;
scanf("%f", &x);
有关数据类型的详细信息,您可以在这里查看:http://en.wikipedia.org/wiki/C_data_types
还有这里:http://www.techonthenet.com/c_language/variables/index.php
【讨论】:
您应该将a 定义为
float a;
并在scanf 中将%d 替换为%f
scanf("%f", &a);
我该怎么办?
【讨论】:
对于 int 变量非常简单,我们使用 %d 格式说明符,如果我们想要浮点数,我们使用 %f 格式说明符。因为根据IEEE int和float位图格式不同。
【讨论】:
你声明 int a 只能取整数值,所以你要做的就是让它浮动,用于带有小数点的数字
浮动一个; scanf(%f,&a);
【讨论】: