我很难有两个功能。以下是项目说明:
分配: 编写一个程序,记录两个相邻房屋中的蟑螂数量,持续数周。房屋中蟑螂的数量将由以下因素确定:
这是我的代码:
#include <iostream>
#include <cmath>
using namespace std;
int house, increase, roaches, moreRoaches, fewerRoaches, filthyBeasts, change; // My variables for my four functions
int initialCount(int house);
int weeklyIncrease(int increase);
double roachesMigration(int moreRoaches, int fewerRoaches, int change);
int exterminationTime (int filthyBeasts);
// My four function prototypes
int main()
{
int houseA, houseB;
houseA = initialCount(houseA); //Initializing the initial count of House A.
houseB = initialCount(houseB); //Initializing the initial count of House B.
int week = 0;
for (week = 0; week < 11; week++) // My for loop iterating up to 11 weeks.
{
houseA = weeklyIncrease(houseA);
houseB = weeklyIncrease(houseB);
cout << "For week " << week << ", the total number of roaches in House A is " << houseA << endl;
cout << "For week " << week << ", the total number of roaches in House B is " << houseB << endl;
if((houseA > houseB)) // Migration option 1
{
roachesMigration(moreRoaches, fewerRoaches, change);
}
else if((houseB > houseA)) // Migration option 2
{
roachesMigration(moreRoaches, fewerRoaches, change);
}
if ((week + 1) % 4 == 0) // It's extermination time!
{
if ((rand() % 2) == 0) // Get a random number between 0 and 1.
{
houseB = exterminationTime(houseB);
}
else
{
houseA = exterminationTime(houseA);
}
}
}
return 0;
}
int initialCount(int house) // Initializing both houses to random numbers between 10 and 100.
{
int num;
num = (rand() % 91) + 10;
return num;
}
int weeklyIncrease(int increaseHouses) // Increasing the roaches in both houses by 30% weekly.
{
int increase = 0;
increase = (increaseHouses * .3) + increaseHouses;
return increase;
}
double roachesMigration(int moreRoaches, int fewerRoaches, int change)
{
more -= change;
fewer += change;
change = ((more - fewer) * .3);
return change;
}
int exterminationTime(int filthyBeasts) // Getting rid of the filthy little beasts!
{
filthyBeasts = (filthyBeasts * .1);
return filthyBeasts;
}
问题在于迁移和消灭功能。我的代码运行正常,但在第4周和第8周,随机选择的房屋应该被消灭,并且该房屋中的蟑螂数量应比前一周减少90%。你认为我应该做些什么来纠正这些问题?我真的需要我能得到的所有帮助!
答案 0 :(得分:2)
关于这一行:
roachesMigration(change);
change
未在您的main
函数中声明,因此出错。此外,roachesMigration
函数需要3个参数而不是1。
答案 1 :(得分:2)
变量change
不是全局变量,而是显示在main
内(因此它在main
内没有任何意义。)
您的roachesMigration
函数是使用三个正式参数声明的(没有默认值),但您将它与一个实际参数一起使用。
请求编译器向您提供所有警告并生成调试信息(Linux上为g++ -Wall -g
)。改进代码直到你没有警告。
学习使用调试器(例如Linux上的gdb
)。
玩得开心。
答案 2 :(得分:1)
根据教师的不同,即使您可以完美地使用此代码,也会获得此代码的零分!这是因为您在构建代码时没有使用任何面向对象的设计。在C ++中,这意味着类。
这个问题需要什么样的对象。一个房子!
你的房子应该有什么样的属性?蟑螂!
这样的事情:
class cHouse
{
int MyRoachCount;
...
};
如果你开始新鲜,就像这样,你会发现事情开始整齐地落到了位置。
答案 3 :(得分:1)
处理迁移的一种可能方法就是这种伪代码:
// compute size of migration
count = migration(houseA, houseB)
if (houseA < houseB)
add count to houseA
subtract count from houseB
else
add count to houseB
subtract count from houseA