【问题标题】:Numbers losing/changing values数字丢失/改变值
【发布时间】: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 programminimal reproducible example 的一个示例,您可以在此处进行测试和发布。

标签: c++ arrays int


【解决方案1】:

这是一个简单的错字。您正在计算分钟和秒,然后只输出mins : mins

displayTime() 函数的最后一行更改为:

cout << mins << " : " << setfill('0') << setw(2) << secs << endl;

我应该提到我通过查看您的输出发现了这一点。看到你打印出来的所有数字都是“x : x”,我怀疑有些东西被意外复制了两次。查看您的 displayTime 函数向我展示了问题。正如@NathanOliver 所说,调试器是一个非常有用的工具,可以在尝试自己解决这个问题时使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2016-08-31
    • 2010-12-22
    • 2023-03-21
    • 2019-04-30
    • 2018-03-19
    相关资源
    最近更新 更多