简体   繁体   English

Class C++ 中的数字

[英]Class Digit in C++

Question:问题:

Please create a class Digit represent a single digit in base ten.请创建一个 class 数字表示以十为底的单个数字。

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. Class 数字应包含两个构造函数,一个没有参数并将数字设置为0,另一个有一个integer 参数并使用该参数设置数字。

Create two function member setDigit and getDigit to set and get the digit int integer type.创建两个 function 成员 setDigit 和 getDigit 来设置和获取数字 int integer 类型。 You should set digit to 0 if setDigit receive a unreasonable parameter.如果 setDigit 接收到不合理的参数,则应将 digit 设置为 0。

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).您可能想要使用 0 和 9 代替 INT_MIN (-INT_MAX - 1) 和 INT_MAX (2^31 - = 2147483647 在我的盒子上)。 You could use a uint8_t instead of int if you wanted.如果需要,可以使用 uint8_t 代替 int。 Also use the same logic in the constructors, ie by calling setDigit() from them:在构造函数中也使用相同的逻辑,即从它们调用 setDigit():

Digit() {
    setDigit(0);
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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