Class C++ 中的数字
Class Digit in C++
问题:
Please create a class Digit represent a single digit in base ten.
Class Digit should contain two constructor, one with no parameter and
set digit to 0, another one with one integer parameter and use the
parameter to set the digit.
Create two function member setDigit and getDigit to set and get the
digit int integer type. You should set digit to 0 if setDigit receive
a unreasonable parameter.
我不知道我的代码错在哪里。
在线法官显示错误答案。
请给我一些想法。
谢谢
#include <limits.h>
class Digit
{
public:
int digit;
Digit()
{
digit = 0;
}
Digit(int n)
{
digit = n;
}
void setDigit(int n)
{
if (n < INT_MIN || n > INT_MAX)
digit = 0;
else
digit = n;
}
int getDigit() const
{
return digit;
}
};
您可能想使用 0 和 9,而不是 INT_MIN(-INT_MAX - 1)和 INT_MAX(2^31 - = 2147483647 在我的盒子上)。如果你愿意,你可以使用 uint8_t 而不是 int 。在构造函数中也使用相同的逻辑,即从它们调用 setDigit():
Digit() {
setDigit(0);
}
Digit(int n) {
setDigit(n);
}
void setDigit(int n) {
digit = (n >= 0 && n <= 9) ? n : 0;
}
问题:
Please create a class Digit represent a single digit in base ten.
Class Digit should contain two constructor, one with no parameter and set digit to 0, another one with one integer parameter and use the parameter to set the digit.
Create two function member setDigit and getDigit to set and get the digit int integer type. You should set digit to 0 if setDigit receive a unreasonable parameter.
我不知道我的代码错在哪里。 在线法官显示错误答案。 请给我一些想法。 谢谢
#include <limits.h>
class Digit
{
public:
int digit;
Digit()
{
digit = 0;
}
Digit(int n)
{
digit = n;
}
void setDigit(int n)
{
if (n < INT_MIN || n > INT_MAX)
digit = 0;
else
digit = n;
}
int getDigit() const
{
return digit;
}
};
您可能想使用 0 和 9,而不是 INT_MIN(-INT_MAX - 1)和 INT_MAX(2^31 - = 2147483647 在我的盒子上)。如果你愿意,你可以使用 uint8_t 而不是 int 。在构造函数中也使用相同的逻辑,即从它们调用 setDigit():
Digit() {
setDigit(0);
}
Digit(int n) {
setDigit(n);
}
void setDigit(int n) {
digit = (n >= 0 && n <= 9) ? n : 0;
}