此问题在此处已有答案:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?(11个回答)
Why does C++ allow missing return value? [duplicate](1个答案)
7天前关闭.
// minicount.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
double evenOut(int arr[], int size, double count) {
double evenCount = count;
if (size == 0) {
return evenCount;
}
if ((arr[size-1] % 2) == 0 ) {
evenCount += 1;
evenOut(arr, size - 1, evenCount);
}
else {
evenOut(arr, size - 1, evenCount);
}
}
double sevenFact(int arr[], int size, double count) {
double sevenCount = count;
string a = to_string(arr[size - 1]);
if (size == 0) {
//cout << "Final total number of 7's -> " << sevenCount << endl;
//cout << "7 to the power of " << sevenCount << " is " << fixed << pow(7, sevenCount) << endl;
return sevenCount;
}
if (a[a.length() - 1] == '7') {
sevenCount += 1;
sevenFact(arr, size - 1, sevenCount);
}
else {
sevenFact(arr, size - 1, sevenCount);
}
}
int main()
{
const string FILE = "randArray.txt";
const int SIZE = 1000;
int arr[SIZE];
ofstream OUTPUTFILE(FILE);
srand(time(NULL));
for (int i = 0; i < SIZE; i++) {
arr[i] = (rand() % 100) + 1;
}
if (OUTPUTFILE.is_open()) {
for (int i = 0; i < SIZE; i++) {
OUTPUTFILE << arr[i] << endl;
}
}
else {
cout << "ERROR: Could not open file." << endl;
}
cout << "EvenOut: The number of even numbers in " << FILE << " is: " << evenOut(arr, SIZE, 0) << endl;
double x = sevenFact(arr, SIZE, 0);
cout << "SevenFact: Total number of numbers ending with 7: " << x;
}
这是我目前的代码设置。我试图打印出这个数组中以7结尾的数字的总数,但是在SevenFact函数调用中返回给x的数字没有正确存储。如果我在sevenFact函数本身中取消注解两行cout,cout打印出正确的总数,但是返回的数字不是这个。
我以同样的方式设置evenCount函数,即正常返回。
但七伯爵有点不对劲,我不知道是什么。
2条答案
按热度按时间jdgnovmf1#
这篇评论更适合你的老师,而不是你;)
看起来你有一个老师(或C源代码)仍然在教你“C”。在C代码中看起来更像这样:
告诉你的老师阅读C++ core guidelines并相应地更新他的材料。你能把这个给他/她看吗?我也很乐意谈论它。
字符串
p8h8hvxi2#
您在
evenOut
和sevenFact
中都缺少return
语句,在进行递归调用时,您需要返回该调用返回的值