[英]Convert char to int in c
Just trying to print the square of a number using macros. 只是尝试使用宏打印数字的平方。 Self explanatory C program : 自我解释的C程序:
#include <stdio.h>
#define numb(a) \
printf(#a * #a)
int main(void) {
int num;
printf("Enter a num: ");
scanf("%d",&num);
numb(num);
return 0;
}
Getting the error : 得到错误:
main.c: In function ‘main’:
main.c:4:14: error: invalid operands to binary * (have ‘char *’ and ‘char *’)
printf(#a * #a)
^
main.c:10:14:
square(num);
~
main.c:10:4: note: in expansion of macro ‘square’
square(num);
^~~~~~
How can I convert that char to int to sucessfully use the binary operator? 如何将char转换为int以成功使用二进制运算符?
Your macro needs to be c code so just ditch the # and write the formatting string for an integer 您的宏需要是C代码,因此只需抛开#并为整数写格式字符串
#include <stdio.h>
#define square(a) \
printf("%d", (a) * (a))
int main(void) {
int num;
printf("Enter a num: ");
scanf("%d",&num);
square(num);
return 0;
}
通过使用“ cc -E main.c -o main.i”检查预处理器阶段的输出,并检查预处理器如何将宏转换为指令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.