#include<stdio.h>
void integer(int *i)
{
char *c;
float *f;
c=(char *)&i;
f=(float *)&i;
printf("value you entered in integer is: %d",*i);
printf("value you entered in character is: %s",*c);
printf("value you entered in float is: %f",*f);
}
int main()
{
int x;
printf("enter any integer:\n");
scanf("%d",&x);
integer(&x);
return(0);
}
这是我试过的代码。如何根据字符和浮点数打印整数?
答案 0 :(得分:1)
无需传递输入的地址。通过价值传递它。然后施展它。那就是:
#include <stdio.h>
void integer(int i)
{
char c;
float f;
c=(char)i;
f=(float)i;
printf("value you entered in integer is: %d\n",i);
printf("value you entered in character is: %c\n",c);
printf("value you entered in float is: %f\n",f);
}
int main()
{
int x;
printf("enter any integer:\n");
scanf("%d",&x);
integer(x);
return(0);
}
答案 1 :(得分:0)
答案 2 :(得分:0)
#include <stdio.h>
void integer(int *i)
{
printf("value you entered in integer is: %d\n",*i);
printf("value you entered in character is: %c\n",(char)(*i));
printf("value you entered in float is: %f\n",(float)(*i));
}
int main()
{
int x;
printf("enter any integer:\n");
scanf("%d",&x);
integer(&x);
return(0);
}
答案 3 :(得分:0)
您是否尝试打印相同值的不同表示,或者您是否尝试将相同的二进制模式解释为不同的值?
用更简单的语言,如果输入整数值100
,是否要显示
value you entered in integer is: 100
value you entered in character is: "100"
value you entered in float is: 100.000000
或
value you entered in integer is: 100
value you entered in character is: d
value you entered in float is: 0.000000
在第一种情况下,你会使用像
这样的东西float f = *i; // conversion happens as part of assignment, no need for cast
char c[N+2]; // where N is the number of digits (10 for 32-bit int, 20 for
// 64-bit)
sprintf( c, "%d", *i );
printf( "value you entered in integer is: %d\n", *i );
printf( "value you entered in chararcter is: \"%s\"\n", c );
printf( "value you entered in float is: %f\n", f );
在第二种情况下,你会做类似
的事情union { int i; float f} u;
u.i = *i;
printf( "value you entered in integer is: %d\n", *i );
printf( "value you entered in chararcter is: %c", (char) *i );
printf( "value you entered in float is: %f\n", u.f );
你不想要
float *f = (float *) i;
或
float f = *(float *) i;
因为违反了严格的别名规则:
6.5表达式
...
7对象的存储值只能由具有其中一个的左值表达式访问 以下类型: 88)
- 与对象的有效类型兼容的类型,
- 与对象的有效类型兼容的类型的限定版本,
- 对应于有效类型的有符号或无符号类型的类型 对象,
- 对应于合格版本的有符号或无符号类型的类型 有效的对象类型,
- 聚合或联合类型,其中包括上述类型之一 成员(包括递归地,子集合或包含的联合的成员)或
- 角色类型