鱼C论坛

 找回密码
 立即注册
查看: 1413|回复: 3

[已解决]C++

[复制链接]
发表于 2021-3-25 23:37:15 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在自定义函数时,如果出现需要返回多个值,应该如何解决?或者有什么替代的方法?
比如说自定义一个比较大小的函数(如比较两个数),想要同时得到比较完成后的两个数。
求帮忙,谢谢
最佳答案
2021-3-26 00:04:29
  1. #include <iostream>

  2. struct input_t {
  3.     int a, b;
  4. };

  5. input_t get_input(std::istream &is) {
  6.     input_t i;
  7.     is >> i.a >> i.b;
  8.     return i;
  9. }

  10. int main() {
  11.     input_t i = get_input(std::cin);
  12.     std::cout << i.a << std::endl << i.b << std::endl;
  13.     return 0;
  14. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-3-26 00:00:10 | 显示全部楼层
用结构体进行打包
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-3-26 00:04:29 | 显示全部楼层    本楼为最佳答案   
  1. #include <iostream>

  2. struct input_t {
  3.     int a, b;
  4. };

  5. input_t get_input(std::istream &is) {
  6.     input_t i;
  7.     is >> i.a >> i.b;
  8.     return i;
  9. }

  10. int main() {
  11.     input_t i = get_input(std::cin);
  12.     std::cout << i.a << std::endl << i.b << std::endl;
  13.     return 0;
  14. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-3-26 01:41:38 | 显示全部楼层
        利用指针传递参数,想返回多少个值都能办到
  1. #include <stdio.h>

  2. void foo(int * a , int * b , int * c)
  3. {
  4.         int t             ;
  5.         if(* a > * b) {
  6.                 t = * b   ;
  7.                 * b = * a ;
  8.                 * a = t   ;
  9.         }
  10.         if(* a > * c) {
  11.                 t = * c   ;
  12.                 * c = * a ;
  13.                 * a = t   ;
  14.         }
  15.         if(* b > * c) {
  16.                 t = * c   ;
  17.                 * c = * b ;
  18.                 * b = t   ;        
  19.         }
  20. }

  21. main(void)
  22. {
  23.         int a = 1000 , b = 100 , c = 10                  ;
  24.         printf("a = %d , b = %d , c = %d\n" , a , b , c) ;
  25.         foo(& a , & b , & c)                             ;
  26.         printf("a = %d , b = %d , c = %d\n" , a , b , c) ;
  27. }
复制代码

        编译、运行实况
  1. D:\00.Excise\C>g++ -o x x.c

  2. D:\00.Excise\C>x
  3. a = 1000 , b = 100 , c = 10
  4. a = 10 , b = 100 , c = 1000

  5. D:\00.Excise\C>
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 15:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表