【发布时间】:2016-04-14 16:49:44
【问题描述】:
我目前正在创建一个程序,旨在将专辑中的 12 首歌曲输入为两组输入的数字,分别为分钟和秒,将它们存储在适当的数组中,然后返回专辑的长度,平均歌曲长度,最短的歌,最长的歌。我当前的几乎所有代码都运行良好,但是我的数字正确时遇到了一些严重的困难。每当我将其格式化为仅秒,然后在格式化为在一位数秒前有一个分号和一个 0 时回到分钟和秒,它们似乎会发生变化。更多解释请看附图。
代码如下:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void displayTime(int);
int main()
{
const int SIZE = 12;
int mins[SIZE], secs[SIZE],minsToSecs[SIZE], totalSecs[SIZE];
int count = 0;
int shortest, longest, totalAlbumLength, averageLengthOfTracks;
cout << "Welcome to my Album Length Calculator" << endl;
cout << "Please enter all track lengths in minutes and seconds" << endl;
cout << "seperated by a space." << endl;
while (count < SIZE)
{
cout << "Track " << count + 1 << ": ";
cin >> mins[count];
cin >> secs[count];
count++;
}
for (int i = 0; i < SIZE; i++)
{
minsToSecs[i] = mins[i] * 60;
}
for (int i = 0; i < SIZE; i++)
{
totalSecs[i] = minsToSecs[i] + secs[i];
}
shortest = totalSecs[0];
for (int i = 0; i < SIZE; i++)
if (shortest > totalSecs[i])
shortest = totalSecs[i];
longest = totalSecs[0];
for (int i = 0; i < SIZE; i++)
if (longest < totalSecs[i])
longest = totalSecs[i];
totalAlbumLength = 0;
for (int i = 0; i < SIZE; i++)
totalAlbumLength += totalSecs[i];
averageLengthOfTracks = totalAlbumLength / SIZE;
cout << "The Shortest track was ";
displayTime(shortest);
cout << "The Longest track was ";
displayTime(longest);
cout << "The Total Album Length was ";
displayTime(totalAlbumLength);
cout << "The Average Track Length was ";
displayTime(averageLengthOfTracks);
system("PAUSE");
return 0;
}
void displayTime(int input)
{
int mins, secs;
mins = input / 60;
secs = input % 60;
cout << mins << " : " << setfill('0') << setw(2) << mins << endl;
}
这里有什么我遗漏的或者我忽略的一些简单的东西吗?
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs
-
使
SIZE等于 1 或 2 并调试您的程序。您不需要 12 项即可看到错误。此外,this minimized version of your program 是 minimal reproducible example 的一个示例,您可以在此处进行测试和发布。