编写一个宏is_digit,如果其参数是十进制数字,则返回true

Write a macro is_digit that returns true if its argument is a decimal digit

本文关键字:参数 如果 十进制数字 true 返回 digit is 一个      更新时间:2023-10-16

我正在尝试解决c++实用编程问题。问题来了。

编写一个宏is_digit,如果其参数是十进制数字,则返回true。编写第二个宏is_hex,如果其参数是十六进制数字(0-9 a-F a-F),则返回true。第二个宏应该引用第一个宏。

这是我的密码。问题是,当输入不是十进制数字时,宏is_digit不会将0返回到digit_res。

有人能帮我哪里出错吗。

#include<iostream>
using namespace std;
#define is_digit(x) (((x)=='0')||((x)=='1')||((x)=='2')||((x)=='3')||((x)=='4')||((x)=='5')||((x)=='6')||((x)=='7')||((x)=='8')||((x)=='9'))
#define is_hex(x) ((is_digit(x))||((x)=='a')||((x)=='b')||((x)=='c')||((x)=='d')||((x)=='e')||((x)=='f')||
((x)=='A')||((x)=='B')||((x)=='C')||((x)=='D')||((x)=='E')||((x)=='F'))
int problem10_3()
{
string x;
int digit_res,hex_res;
cout<<"Enter Decimal or Hexadecimal:";
cin>>x;
digit_res=is_digit(x);
if(digit_res==1)
    cout<<"You have entered Decimal digit"<<endl;
else
{
 hex_res=is_hex(x);
 if(hex_res==1)
     cout<<"You have entered Hexadecimal digit"<<endl;
 else
     cout<<"You have not entered either Decimal or Hexadecimal"<<endl;
}
return 0;
}

提前感谢

实际上是向后的。您"返回"0而不是1,反之亦然。无意冒犯,但很难将其视为愚蠢的拼写错误。

此外,您正在使用字符文字'x'而不是任何变量"调用"宏。首先,您可能想传递&x[0],或者从stdin读取char

有一个标准库std::isdigit函数,以及用于十六进制的std::isxdigit,但如果您真的觉得有必要编写宏,则可以在不使用三元或相等比较的情况下编写

#define is_digit(x) ('0' <= (x) && (x) <= '9')

使用三元是不必要的

(a == b ? 1 : 0)

与写入相同

(a == b)

如果你的目标是在编译时计算值,那么你应该使用constexpr函数

constexpr bool is_digit(char x) {
    return '0' <= x && x <= '9';
}

您有的逻辑吗?反向

<condition> ? <if true> : <if false>

也是

#define is_digit(x) (((x)=='0')||((x)=='1')||((x)=='2')||((x)=='3')||((x)=='4')||((x)=='5')||((x)=='6')||((x)=='7')||((x)=='8')||((x)=='9'))?1:0

正如我之前所说的-不要在c++中做宏-使用内联函数

正如nnn在评论中所说,你也有这个

digit_res=is_digit('x');

你是说

digit_res=is_digit(x);
相关文章: