如何从temp结构变量传递变量用于多个struct变量(永久存储)

时间:2014-09-28 23:41:40

标签: c++ struct

我在C ++中得到了这段代码,其主要任务是计算两次之间的差异。首先,它应该为两个结构变量赋值。之后它应该找出哪个时间首先开始。它要做的最后一件事是计算时间之间的差异。

我对这段代码的问题不在于我无法将变量从一个临时结构变量传递给另一个变量,问题是当我从temp结构变量第二次传递到第二个struct变量时,变量来自第一个struct变量被程序忘记了。反正让变量传递给结构变量吗?

这是我的代码:

#include <iostream>
using namespace std;

const int maxAddTime = 141; // 23 hours + 59 min. + 59 sec.
const int minAddTime = 0;
int addTime;

char choice;

bool done = false;

struct timeset {
   int hour;
   int minute;
   int second;
};

int main(){
    timeset time1, time2, temp;
   do {                  
     int times = 1;
        while (times <=2) {
            do {
            cout << "Write your " << times << " time (hh mm ss)" << endl;
            temp = (times == 1) ? time1 : time2;
            cin >> temp.hour >> temp.minute >> temp.second;
            int addTime = temp.hour + temp.minute + temp.second;

            if ( addTime < minAddTime || addTime > maxAddTime) {
               cout << "Invalid time!" << endl;
               cout << "Do you want to change the time? (Y)es or (N)o?" << endl;
               cin >> choice;
            }
            else { 
               choice = 'n'; 
               times++;

            }

            if (times == 1){
            time1 = temp;
            cout << time1.minute ;
            }
            else {
            time2 = temp;
            cout << time2.minute << endl;
            }

            break;
            }
            while ( choice != 'n' || choice != 'N');
         }   

      if (time1.hour > time2.hour || time1.minute > time2.minute ||
          time1.second > time2.second) {        
         cout << "The first time comes first!\n";
      }
      else if ( time1.hour < time2.hour || time1.minute < time2.minute || 
                time1.second < time2.second) {
             cout << "The second time comes first!\n";
      }
      else {
         cout << "The times are equal!\n";
      }

      int addTime =  time1.hour + time1.minute + time1.second;
      cout << addTime << endl;
      addTime = addTime - (time2.hour + time2.minute + time2.second);

      cout << addTime << endl << endl;
   }
   while (!done);
   return 0;
}

1 个答案:

答案 0 :(得分:1)

在检查其值之前,您正在递增“时间”:

 else { 
               choice = 'n'; 
               times++;

            }

因此,当您在第一次输入后到达此处时,时间已设置为2,并且永远不会满足第一个条件。将时间++移动到循环的末尾;

    if (times == 1){
    time1 = temp;
    cout << time1.minute ;
    }
    else {
    time2 = temp;
    cout << time2.minute << endl;
    }

    /// other code
    times++;

此外,您不能简单地将不同的时间单位加在一起(hr + mins + sec)并获得任何有意义的结果。您需要将每个时间组件规范化为一个公共单位 - 最有可能是秒。所以,计算如下:

int addTime =  time1.hour*60*60 + time1.minute*60 + time1.second;