简体   繁体   English

C/C++ 中的原型设计

[英]Prototyping in C/C++

I am trying to create the prototype and write the function called average.我正在尝试创建原型并编写名为 average 的函数。

I am not sure how to create it, what have gets the errors too few arguments to function..... on both lazlo and pietra我不知道如何创建它,在 lazlo 和 pietra 上有什么错误参数太少而无法运行.....

Average receives an array of student test scores.平均接收一组学生考试成绩。

average computes the average of the student's scores average 计算学生分数的平均值

how do i properly create the prototype?我如何正确创建原型?

#include <iostream>
using namespace std;

double average( int array[], int items); // function declaration (prototype)

int main()
{
    int lazlo[] = {90, 80, 85, 75, 65, -10};
    int pietra[] = { 100, 89, 83, 96, 98, 72, 78, -1};
    int num;

    num = average( lazlo );
    cout << "lazlo took " << num << "tests. Average: " << lazlo[ num ] << endl;

    num = average( pietra );
    cout << "pietra took " << num << "test. Average: " << pietra[ num ] << endl;

    // function call to average

}

You've declared average to take two arguments: (a pointer to the first element of) an array and the number of items in the array.您已声明average接受两个参数:(指向第一个元素的指针)数组和数组中的项数。 The problem is that when you call average you only pass it one argument: the array (which decays into a pointer to its first element).问题在于,当您调用average您只传递一个参数:数组(衰减为指向其第一个元素的指针)。 You're missing the items argument.您缺少items参数。

Your call should look something like this:你的电话应该是这样的:

num = average(lazlo, 6);

The messages you print afterward are also incorrect.之后打印的消息也不正确。 average returns the average value, so num will be the average of the numbers in your array, not the number of items. average返回平均值,因此num将是数组中数字的平均值,而不是项目数。 Additionally lazlo[num] will be an error, since num will be 64 , and there is no 64th item in your lazlo array.此外, lazlo[num]将是一个错误,因为num将为64 ,并且您的lazlo数组中没有第 64 项。

You need to have an actual function associated with the prototype in order for your code to work.您需要有一个与原型相关联的实际函数才能使您的代码工作。 You can add this below your main function:您可以将其添加到您的主要功能下方:

double average( int array[], int items) {
  // write your averaging code here
}

Once you have finished coding the average function, make sure to call it such that the number of inputs and datatypes match your prototype:完成对平均函数的编码后,请确保调用它以使输入的数量和数据类型与您的原型相匹配:

num = average(lazlo, 6);
num = average(pietra, 8);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM