gpt4 book ai didi

c - 反向打印字符串而不在代码中反转

转载 作者:行者123 更新时间:2023-11-30 19:01:38 26 4
gpt4 key购买 nike

我尝试通过三元运算符声明它来打印字符串。它不会出现任何错误,而是相反地打印字符串。

有人可以解释一下吗?

我期望根据输入将字符串打印为

 #include<stdio.h>

void main()
{
int a;
char *num;

printf("Enter a number: ");
scanf("%d", &a);

num = (a % 2) ? 'odd' : 'even';

printf("Its %s number", &num);

getch();
}

最佳答案

'odd''even' 是整型字符常量。

根据C标准(6.4.4.4字符常量)

10 An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

所以在这次通话中

printf("Its %s number", &num);

您正在尝试将变量num的地址输出为字符串的地址,即您正在尝试输出字符串,但num并不指向字符串。

您必须使用字符串文字而不是字符常量。

你的意思是下面的内容

    num = (a % 2) ? "odd" : "even";

printf("Its %s number", num);

关于c - 反向打印字符串而不在代码中反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57475754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com