简体   繁体   中英

Class Digit in C++

Question:

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.

I don't know how wrong to my code. The online Judge displayed wrong answer. Please give me some idea. Thanks.

#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;
  }
};

You probably want to use 0 and 9 inclusive instead of INT_MIN (-INT_MAX - 1) and INT_MAX (2^31 - = 2147483647 on my box). You could use a uint8_t instead of int if you wanted. Also use the same logic in the constructors, ie by calling setDigit() from them:

Digit() {
    setDigit(0);
}

Digit(int n) {
    setDigit(n);
}

void setDigit(int n) {
    digit = (n >= 0 && n <= 9) ? n : 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM