2015-06-05 226 views
-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",*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); 
} 

这是我试过的代码。我怎样才能打印字符和浮点的整数?当我试图使用字符类型,浮点类型打印整数值时,为什么它不起作用?

+1

*我怎样才能打印字符和浮点数的整数?*你想用这个来实现什么? –

+0

这是我参加测验考试时所得到的其中一个问题...... –

+1

这么一小段代码中的错误太多了。首先,你将'int * i'传递给函数,所以你应该删除后面两个铸件中的'&'(或者传递'int i')。第二,打印'“...%s”,* c' - 你希望打印什么,字符或字符串?如果是字符,则使用'%c'而不是'%s'。如果是字符串,则使用'c'而不是'* c'。请注意,对于'%s',这是非常不安全的,并且通常会产生未定义的行为,因为'c'不一定指向以空值终止的字符串(在内存边界内)。 –

回答

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); 
} 
+0

我试过上面的程序,你已经给出,但它是在整数值打印后停止.....顺便说一句,我需要通过使用指针得到它。 –

+0

对不起,我忘了编辑%s到%c现在运行它@PrasanthSai –

+0

是的我知道了,但通过使用指针问。 –

0

您正在打破Strict aliasing rule最终导致不确定的行为。

假设你想使用它的ASCII值打印出来的人物,那么你可以这样做:

printf("%c\n",i); 
+0

使用指针怎么样? –

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); 
    } 
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表达式
... - 一个类型与有效类型的对象的兼容,
- 的一个合格的版本 88)

7所述的对象应具有其存储的值由具有 之一以下类型的一个左值表达式仅访问与对象的有效类型兼容的类型,
- 对应于 对象的有效类型的有符号或无符号类型的类型,
- 与合格版本对应的有符号或无符号类型的类型对象的有效类型 ,
- 聚合或联合类型包括其 成员之间的上述类型的一个(包括递归地,一个子聚集或含有联合的成员),或
- 字符类型
相关问题