编写一个宏is_digit,如果其参数是十进制数字,则返回true
Write a macro is_digit that returns true if its argument is a decimal digit
我正在尝试解决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);
相关文章:
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 如果返回 -1,时间() 的参数是否被修改?
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 如果需要转换,我可以在读取参数的同时将其移动到另一个参数吗?
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- 如果参数与数据成员的参数同名,该怎么办?
- 如果条件,当我想第二个参数时
- Qt5:连接:如果插槽的参数少于信号,如何使用"连接"
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 是否可以将带有捕获和参数的 lambda 传递给另一个函数?如果是这样,如何?
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- 使用 std::move 将参数传递给函数,如果该参数声明为按值传递或使用移动操作数 &&,是否有区别?
- 如果模板模板参数是矢量,则需要不同的行为
- C++14 及更高版本是否允许 Lambda 函数的默认参数?如果是这样,怎么办?
- 何时在 c++ 中使用参数(如果有的话)?
- 函数还是函子作为模板参数?(如果不需要状态)
- 提升:取消引用模板参数(如果它是指针)
- make_heap() 函数参数 - 如果我不想包含某些元素怎么办?