我多次编译代码,并收到与内存相关的运行时错误。我是编程新手,无法解决问题。如果有人可以帮助我理解为什么会这样,并给我一些有关清理代码/提高代码效率的提示,我将不胜感激!
#include <iostream>
#include <cmath>
void chefsMenuitems();
void chefsMenuitems(int P[], int arr_size) {
int count = 0;
int current_item = 0;
int n = 0;
int i = 0;
for (int j = 0; j < arr_size; j++ ) {
while(P[j] > 0) {
for ( i = 0; current_item < P[j]; i++) {
current_item = pow(2,(i));
if (current_item > P[j]){
current_item = pow(2,(i - 1));
break;
}
}
P[j] = P[j] - current_item;
current_item = 0;
n++;
}
count++;
std::cout << "The number of menu items for price " << count << " are: " << n << "\n";
n = 0;
current_item = 0;
}
}
int main() {
int T = 0;
int P[] = {0};
int arr_size;
std::cout << "Please enter the number of test cases: \n";
std::cin >> T;
while(T < 1 || T > 5 ) {
std::cout << "Test cases must be between 1 & 5 inclusive: \n";
std::cin >> T;
}
arr_size = T;
for (int i = 0; i < T; i++) {
std::cout << "Please enter the amount you are willing to spend: \n";
std::cin >> P[i];
while(P[i] < 1 || P[i] > pow(10, 5)) {
std::cout << "The amount you are willing to spend must be between 1 and 10^5 inclusive: \n";
std::cin >> P[i];
}
}
chefsMenuitems(P, arr_size);
return 0;
}
答案 0 :(得分:0)
您的
int P[] = { 0 };
是一个元素的数组,但是您尝试访问最多5个元素。
如果您想要一个类似数组的容器,其大小在编译时未知,请使用std::vector<int>
,或者通过为预期输入定义一个尽可能大的数组来浪费一些空间:
int P[5] = {};