我想解决的问题是:
为了解决这个问题,我编写了以下代码:
#include<iostream>
#include<cmath>
using namespace std;
int computervirus(int n){ //n:Tage
int nr_virus= 100;
int nr_fixed;
int rest = 0;
if(n == 0) return 100;
if(n <= 20){
nr_virus += computervirus(n-1)*0.7;
nr_fixed = pow(2,n);
rest = nr_virus - nr_fixed;
}
return rest;
}
int main(){
cout << endl;
for(int i=0; i <= 20; i++){
cout << "at the "<< i << " .day are still "<< computervirus(i) << " infected Computers\n" <<endl;
}
return 0;
}这个数目的输出(受感染的计算机)是不正确的,因为感染的速度肯定是更快的als修理至少前9天。我不知道问题在哪里。你能帮上忙吗?
发布于 2019-02-16 22:35:53
第n天的递归尝试使用n+1结果的70%,这将导致无限递归。你必须使用70%的第一天,它将工作。现在不是前一天的70%,而是70%,不是* 0,7,而是* 1,7。
你需要考虑到电脑感染的人数不可能是负数。
最后,你高估了修理:第一天是2天,第2天是4天,但是由于第1天的第2天已经被计算在第1天的递归中,所以你推断了两次。所以你应该只计算固定日期的电脑,所以就算(2,n-1)。
修正后的代码如下所示:
int computervirus(int n){ //n:Tage
int nr_virus= 100;
int nr_fixed = 0;
int rest = 0;
if(n>0){
nr_virus = computervirus(n-1)*1.7; // n-1 not n+1
if (n==1)
nr_fixed = 2;
else nr_fixed = pow(2,n-1);
}
rest = nr_virus - nr_fixed;
if (rest<0)
rest = 0;
return rest;
}发布于 2019-02-16 22:09:03
您忘了在for循环的主体上使用大括号。
int main(){
for(int i=0; i <= 20; i++)
{
cout << endl;
cout << "at the "<< i << " .day are still "<< computervirus(i) << " infected Computers\n" <<endl;
}
return 0;
}在循环中的第一个语句之前放置一个左大括号{,在最后一个语句后面放置一个右大括号}。
因为大括号只缺少第一个语句,所以cout << endl;在循环中。
https://stackoverflow.com/questions/54728117
复制相似问题