cddyy2366 发表于 2020-10-1 00:41:27

C++问题求助

大佬们我做了一个24小时制转为12小时制的程序,然后分别用了两个结构体,把输入时间,时间转换,输出时间分成了三个函数,但是现在转换函数部分的数值并不是我在输入时间函数里输入的数,我觉得应该是输入的数据没有保存到结构体里,但是不知道该怎么改。可以帮我看一下哪里有问题吗。谢谢!
代码如下
#include <iostream>
#include <string.h>

using namespace std;

struct twentyfour{
        int hour;
        int minute;
};

struct twelve{
        int hour;
        int minute;
        char a;
};

int getdata(struct twentyfour m)
{
        cout<<"Please input the time:";
        cin>>m.hour>>m.minute;
}

int conversion(struct twentyfour m,struct twelve n)
{
        if(m.hour>=13 && m.hour<=23)
        {
                n.hour=m.hour-12;
                n.minute=m.minute;
                strcpy(n.a,"PM");
        }
       
        if(m.hour<=12)
        {
                n.hour=m.hour;
                n.minute=m.minute;
                strcpy(n.a,"PM");
        }
}

int showdata(struct twelve n)
{
        cout<<"\nThe time after changing is:";
        cout<<n.hour<<":"<<n.minute<<n.a;
}

int main()
{
        struct twentyfour m;
        struct twelve n;
       
        int number;
        cout<<"******************************************************";
        cout<<"\n1:Show the time after changing.";
        cout<<"\n2:Exit.";
       
        while(1)
        {
                cout<<"\nPlease choose the number:";
                cin>>number;
               
                switch(number)
                {
                        case 1:
                                getdata(m);
                                conversion(m,n);
                                showdata(n);
                                break;
                       
                        case 2:
                                return 0;
               
                        default:
                                cout<<"\nWrong number!";
                }
        }
       
        return 0;
}

召唤风云 发表于 2020-10-1 01:28:48

你要用指针或者引用

km82805046 发表于 2020-10-3 03:13:27

本帖最后由 km82805046 于 2020-10-3 03:36 编辑

int getdata(struct twentyfour &m)   //使用引用传递参数
{
      cout<<"Please input the time:";
      cin>>m.hour>>m.minute;
      return 0;
}

int conversion(struct twentyfour &m,struct twelve &n)   //使用引用传递参数
{
      if(m.hour>=13 && m.hour<=23)
      {
                n.hour=m.hour-12;
                n.minute=m.minute;
                strcpy(n.a,"PM");
      }

      if(m.hour<=12)
      {
                n.hour=m.hour;
                n.minute=m.minute;
                strcpy(n.a,"AM");
      }
      return 0;
}

int showdata(struct twelve &n) //使用引用传递参数
{
      cout<<"\nThe time after changing is:";
      cout<<n.hour<<":"<<n.minute<<n.a;
      return 0;
}

将3个函数传递参数用引用实现即可!
页: [1]
查看完整版本: C++问题求助