【发布时间】:2020-03-03 18:09:34
【问题描述】:
此测试出错:- https://www.hackerrank.com/challenges/30-class-vs-instance/problem?h_r=next-challenge&h_v=zen 一个测试用例由于某种原因失败了,当我在我的 IDE 中运行它时,它给出了与预期相同的输出,帮助我找出我错过了什么,我是非常初学者级别的编码器,从 Civil Engg 背景移动,所以如果出现错误,我很抱歉真的很傻。我的代码:
#include <iostream>
using namespace std;
class Person{
public:
int age;
Person(int initialAge);
void amIOld();
void yearPasses();
};
Person::Person(int initialAge){
if (initialAge < 0){
this->age=0;
cout << "Age is not valid, setting age to 0.";
}
else {
this->age = initialAge;
}
}
void Person::amIOld(){
if(age < 13){
cout << "\nYou are young.";
}
else if (age >= 13 && age < 18) {
cout << "\nYou are a teenager.";
}
else {
cout << "\nYou are old.";
}
}
void Person::yearPasses(){
age++;
}
int main(){
int t;
int age;
cin >> t;
for(int i=0; i < t; i++) {
cin >> age;
Person p(age);
p.amIOld();
for(int j=0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
cout << '\n';
}
return 0;
}
【问题讨论】:
-
顺便说一句,您可以通过不使用
this->来节省一些打字时间。直接访问变量:例如age = initialAge;构造函数不需要this->表示法,并且您不要在其他方法中使用该表示法。 -
也许是你的换行处理。在年龄小于 0 的 ctor 中,您不会打印换行符。但是在
amIOld中,您在文本之前打印换行符。 -
请注意,
else if测试中可以省略age >= 13 &&部分! -
明白了!摆脱了那个年龄 >= 13 的条件,因为它没有用