来自数组的C ++函数未正确调用

时间:2016-12-14 03:12:14

标签: c++ arrays function math

我遇到了功能2,3和4的问题。我认为我必须有一些逻辑错误,因为我的思想无法解决问题所在。每次调用函数时,它们都应该执行它们的算术运算。例如,每次调用* 2函数时,它应该将数组中的值乘以2。它只执行一次,但保持该值。我需要让它每次乘以(在这个例子中)数组中的整数。我对C ++很陌生,并希望得到关于这些函数中会出现什么问题的任何反馈。

这就是我所拥有的:

#include<iostream>
using namespace std;



void initialize (int a[])
{
    for (int i=0; i<=9; i++)
    {
        a[i] = i;
    }
}



void times2 (int a[])
{
    for (int i=0; i<=9; i++)
    {
        a[i] = i*2;
    }
}



void halve (int a[])
{
    for (int i=0; i<=9; i++)
    {
    a[i] = i/2;
    }
}



void square(int a[])
{
    for (int i=0; i<=9; i++)
    {
    a[i] = i*i;
    }
}


void shiftleft(int a[])
{
    int temp=a[0];
    for (int i=0; i<=8; i++) 
    {
       a[i] = a[i+1];
    }
    a[9]=temp;
}


void shiftright(int a[])
{
    int temp=a[9];
    for (int i=9; i>=0; i--) 
    {
       a[i] = a[i-1];
    }
    a[0]=temp;
}




int main()
{
    int numbers[10];   // a 10 element array of integers, numbers[0]...numbers[9]
    int option;

    initialize(numbers);

    do
    {

        cout << "\nYour array of numbers\n";

        for(int i=0; i<=9; i++)
            cout << numbers[i] << " ";

        cout << "\n\nPlease Select and Option \n\n";
        cout << "   1. Initialize\n";
        cout << "   2. Double\n";
        cout << "   3. Halve\n";
        cout << "   4. Square\n";
        cout << "   5. Shift Left\n";
        cout << "   6. Shift Right\n";
        cout << "   or any other number to exit\n";
        cin >> option;

        if (option ==1)
            initialize(numbers);

        else if (option == 2)
            times2(numbers);

        else if (option == 3)
            halve(numbers);

        else if (option == 4)
            square(numbers);

        else if (option == 5)
            shiftleft(numbers);
        else if (option == 6)
            shiftright(numbers);

    }
    while ((option >= 1) && (option <= 6));


    return 0;
}

3 个答案:

答案 0 :(得分:1)

如果希望times2函数将当前数组元素值乘以2,则必须具体执行以下操作:获取当前数组元素值,将其乘以2并将其存储回数组元素< / p>

for (int i=0; i<=9; i++)
{
    a[i] = a[i] * 2;
}

您当前的实现完全忽略现有的数组元素值,只需将每个a[i]重新初始化为i * 2

每个修饰符函数都存在同样的问题。

答案 1 :(得分:0)

void times2 (int a[])
{
  for (int i=0; i<=9; i++)
  {
     a[i] = a[i]*2;
  }
}

void halve (int a[])
{
  for (int i=0; i<=9; i++)
  {
    a[i] = a[i]/2;
  }
}

答案 2 :(得分:0)

您正在做的是使用操作索引而不是您想要使用的实际值。你没有得到你想要的值的原因是因为我是索引 - 它指的是数组的位置,而不是数组本身包含的值

假设我们有一个数组:

a = [5, 10, 15, 20, 25, 30, 35, 40, 45]

此数组有9个值,因此有9个索引位置或索引。但由于C ++是零索引的(即位置从0开始),索引编号为:

i = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

因此,您可以通过在方括号中输入索引来引用数组的第i个值。例如,如果你想要for循环中第4个元素的,当 index i = 3时,你会得到:

a[i] = 20

因此,在你的times2函数的情况下,你将索引而不是相乘。替换:

a[i] = i*2;

a[i] = a[i]*2

关于你的其他功能也可以这样说。