首页 > 解决方案 > 在 C++ 中使用布尔函数匹配总和

问题描述

我编写了这个程序,该程序应该解决数字从 1 到 11 的轮子,但我无法找出导致此链接器错误的原因。我相信除了这个使用整数数组的布尔函数之外,我在代码主体中的所有其他内容都可以正常工作,但是出现的错误如下所示。我不确定我在功能上做错了什么。我在代码的开头使用原型声明了它,我使用它的正确名称调用函数并正确调用数组。有人可以帮我弄清楚代码有什么问题吗?

对“matchingSums(int)”的未定义引用……重定位被截断以适应:R_X86_64_PC32 针对未定义符号

#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <time.h>
using namespace std;


const int MAX_CIRCLES = 11;
const int CENTER_CIRCLE_INDEX = 10;
bool matchingSums(int);
void fillTheWheel(int []);
void displayWheelContents(int []);
void randomizeTheContents(int, int []);
int nbrOfItems, firstSum, nextSum;
int main(void)
{

srand(time(NULL));

int wheel[MAX_CIRCLES];

int numInt = 0;
fillTheWheel(wheel);

while (!matchingSums(*wheel))
{

numInt++;

randomizeTheContents(MAX_CIRCLES, wheel);
}
cout << "After " << numInt << " unsuccessful attempts, the following solution was found:" << endl;
displayWheelContents(wheel);
}


void fillTheWheel(int wheel[])
{

for (int fillTheWheelIndex = 0; fillTheWheelIndex < MAX_CIRCLES; fillTheWheelIndex++)
{
wheel[fillTheWheelIndex] = (fillTheWheelIndex + 1);
}
}
void displayWheelContents(int wheel[])
{

cout << "* Outside circles (clockwise from the top):" << endl << " " << endl;

for (int wheelIndex = 0; wheelIndex < MAX_CIRCLES; wheelIndex++)
{
// Print each value in a column width of 4 as shown in the example-program-execution.txt file
cout << setw(4) << wheel[wheelIndex] << " ";
}

cout << " " << endl << " " << endl << "*Center circle: " << wheel[CENTER_CIRCLE_INDEX] << endl;
}

void randomizeTheContents(int nbrOfItems, int table[])
{

for (int indexA = 0; indexA < nbrOfItems; indexA++)
{
int indexB = rand() % nbrOfItems;
int temp = table[indexA];
table[indexA] = table[indexB];
table[indexB] = temp;
}
}

bool matchingSums(int wheel[])
{
const int MAX_OUTER_CIRCLES = MAX_CIRCLES - 1;
const int OPPOSITE_SIDE_FACTOR = 5;
const int STARTING_INDEX = 0;
int firstSum;
int nextSum;
// Calculate the sum of the first pair of numbers
firstSum = wheel[STARTING_INDEX] + wheel[CENTER_CIRCLE_INDEX] 
+ wheel[STARTING_INDEX + OPPOSITE_SIDE_FACTOR];
// Compare the first sum to each of the sums of the other pairs
for (int i = 1; i < MAX_OUTER_CIRCLES/2; i++)
{
nextSum = wheel[i] + wheel[CENTER_CIRCLE_INDEX] + wheel[i + OPPOSITE_SIDE_FACTOR];
if (firstSum != nextSum)
return false; 
} // End for

return true;
} // End matchingSums

标签: c++arraysreferenceboolean

解决方案


最初,该函数是用一个类型的参数声明int

bool matchingSums(int);

int 并使用main类型的参数调用

while (!matchingSums(*wheel))

但是在它的定义中,它是用int []编译器隐式调整为int *类似类型的类型的参数声明的

bool matchingSums(int wheel[])

所以编译器发出一个错误,因为它没有找到声明的函数的定义

bool matchingSums(int);

推荐阅读