微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C ++,功能随着输入量的变化而变化idk如何描述

如何解决C ++,功能随着输入量的变化而变化idk如何描述

函数HIGHEST都很好,并且接受可变数量的参数。问题是我如何进行可变数量的输入? (idk应该使用什么术语来描述它,但是示例应该可以清除问题...)

/ * cout 这是我想要实现的, 但是有变化-数组的数量随着 输入文件,n定义其中的多少个。 例如:如果n = 7,则需要为(n,A [0],A [1],A [2],A [3],A [4],A [5],A [6]) * /

Duom.txt文件,如果需要的话(我现在仅使用第1个数字4,其他文件将与第1行相同/相似,因此它们现在不重要了

4

2008 5 2000.00 400.25

2010 5 4000.00 320.25

2009 9 3385.00 254.45

2008 6 1900.00 612.59

#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <cstdarg>

using namespace std;
//Variable number of arguments in C++
int highest (int num,...) {
   va_list valist;
   int max = 0;
   int a;
   va_start(valist,num);
   for (int i = 0; i < num; i++) {
        a = va_arg(valist,int);
        if(max < a) max = a;
        else ;
   }
   va_end(valist);
   return max;
}




int main () {
int n,A[25],B[25];
double C[25],D[25];

ifstream fd ("Duom.txt");
ofstream fr ("Rez.txt");
fd >> n;
cout << n <<endl;
for(int i = 0; i < n; i++){
    fd >> A[i] >> B[i] >> C[i] >> D[i];
}
cout << highest(n,) <<endl;
/*cout << highest(n,A[0],A[1],A[2],A[3]) <<endl;  
this is what I would like to achieve,but with a change - the number of array changes with 
the input file and n defines how many of these will be. 
ex.: if n = 7 it needs to be (n,A[3],A[4],A[5],A[6])
*/


    return 0;
}

解决方法

您是否有特定的原因想要函数Highest单独获取所有数组整数?另外-为什么选择使用数组而不是向量?

假设您要使用数组,我建议如下更改函数的参数:

int highest (int num,int *arr);

其中,arr是数组的名称,实际上是指向数组第一个整数的指针。 然后,在函数内部,您可以使用下标符号或取消引用访问数组:

first_array_int=*(arr); //dereferencing example
second_array_int=*(arr+1); //dereferencing example

first_array_int=arr[0]; //subscript example
second_array_int=arr[1]; //subscript example

请注意,这样做可以更改函数中传递的数组。

同样,我建议改用向量,然后定义函数:

int highest (int num,vector <int> *A);

如果要传递指针,或者:

int highest (int num,vector <int> A);

如果要按值传递。当然,不要忘记在向量库中加入

#include <vector>

希望我能很好地理解您的问题,这对您有帮助。

祝你好运!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。