所以我正在尝试创建一个程序,它接受一些随机数的输入秒数并将其转换为Days,Hours,Minutes和Seconds。我不得不使用符号常量来定义一天中的小时数,一小时内的分钟数和一分钟内的秒数。我通过了价值,但它没有被收到,所以我最终得到了一些巨大的负数。这是代码。如果有人能告诉我问题所在,我会感激不尽。
我在函数定义代码中使用了随机位代码来显示总秒数以查看它是否被收到而且不是。
#ifndef SECONDS_H_
#define SECONDS_H_
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60
#include <iostream>
using namespace std;
class Seconds
{
private:
long totalSeconds;
public:
Seconds();
~Seconds(){};
Seconds(int totalSeconds);
void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds);
};
#endif
...
#include <conio.h>
#include <string>
#include <iostream>
#include "seconds.h"
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTE 60
Seconds::Seconds(int totalSeconds)
{
totalSeconds = totalSeconds;
}
void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds)
{
cout << endl;
cout << "Total Seconds: " << totalSeconds;
cout << endl;
days = totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE / HOURS_IN_DAY;
hours = (totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE) % HOURS_IN_DAY;
minutes = (totalSeconds / MINUTES_IN_HOUR) % SECONDS_IN_MINUTE;
seconds = (totalSeconds % SECONDS_IN_MINUTE);
}
...
#include <iostream>
#include <conio.h>
#include <string>
#include "seconds.h"
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60
using namespace std;
int main ()
{
int totalSeconds;
int days = 0, hours = 0, minutes = 0, seconds = 0;
cout << "Enter a random massive amount of seconds: ";
cin >> totalSeconds;
Seconds sec(totalSeconds);
sec.convertSeconds(days, hours, minutes, seconds);
cout << "That is equivalent to " << days << " days, " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds." << endl;
cout << "Press any key to continue...";
cin.sync();
_getch();
return 0;
}
答案 0 :(得分:5)
这是一个问题:
Seconds::Seconds(int totalSeconds)
{
totalSeconds = totalSeconds;
}
函数参数totalSeconds
会影响类成员,因此此代码就像执行x = x;
一样,它对this->totalSeconds
没有影响。
要修复此问题,请使用不同的变量名称,或者最好使用构造函数初始化语法:
Seconds::Seconds(long totalSeconds)
: totalSeconds(totalSeconds)
{
}
在此版本中,不会发生阴影,因为构造函数初始化列表是智能的。
答案 1 :(得分:0)
您是否认为问题可能是Integer Overflow?