【发布时间】:2014-05-19 02:35:03
【问题描述】:
所以我正在尝试制作一个程序,该程序需要随机输入的秒数并将其转换为天、小时、分钟和秒。我必须使用符号常量来定义一天中的小时数、一小时内的分钟数和一分钟内的秒数。我通过了这个值,但它没有被接收,所以我最终得到了一些巨大的负数。这是代码。如果有人能告诉我问题出在哪里,我将不胜感激。
我使用函数定义代码中的随机代码位来计算总秒数,以查看它是否被接收。
#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;
}
【问题讨论】:
-
您提供的“秒”值是多少?您是否尝试将其打印出来或在调试器中显示?
-
另外,当你声明类时,你不应该在方法声明中使用类名:
void Seconds::convertSeconds。一些编译器会对此发出警告,而另一些编译器则不会根据编译器设置来编译你的东西。这是一个品味问题,但如果你有很多 func 参数,那么我认为最好将这些值打包到一个结构中并将结构引用或结构 const 引用传递给函数。以后添加更多参数更容易。虽然执行函数调用需要更多的行,但代码变得更具可读性。