+ 1
Can someone help me identify my mistake in my C++ code? How do I display 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/64 = 0.984375?
I'm using terminal. Those of you who are able to help me will be greatly appreciated. https://code.sololearn.com/c2NfhQIZZ06P/?ref=app
8 Respuestas
+ 8
SubLime56 You can fix your attempt fairly easily.
// you redeclared denom inside the loop, you only need one declaration. Set its value outside the loop.
//The for loop structure is wrong. The loop only needs to run 6 times in your code. Not 64. Try using a while loop or restructure the for loop conditions.
Here is the fixes. Please study the changes.
Rajeebs code is also a good example for solving this problem. I would recommend studying his solution.
#include <iostream>
using namespace std;
int main()
{
// you redeclared denom inside the loop.
int denom = 2;
int finalDenom = 64;
double sum = 0.0;
cout << "My Name. \n\n";
// first cout should be outside the loop
cout << "1/" << denom;
// should be while loop, program loops like 6 times, not 64
//for (int i = 1; i < finalDenom; i++) {
while(denom != finalDenom) {
sum += 1.0/denom;
denom = denom * 2;
if (denom != finalDenom) {
cout << " + 1/" << denom;
}
// else case needs a full set of cout text
else if (denom == finalDenom) {
cout << " + 1/" << denom << " = " << sum << endl;
}
}
return 0;
}
+ 2
hi,
use this link
i have refreshed working code:
https://code.sololearn.com/cSf70t7DAuYT
+ 1
yes, it displays
try it in c++
but in computer /laptop
+ 1
@SubLime56
hi,
does this solve your problem
reply
+ 1
that's very easy
just use the input variable
stated in the program
as your constant input
and
remove the printf asking line from user
0
@Rajeeb
Is there a way where it only displays the series of fractions and it's sum.
0
@Rajeeb
Your code works perfectly, but I'm trying to display the fractions and it's sum only without inputing a value.
0
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double sum =0;
for (int n =1; n<=6;n++)
sum = sum + 1/pow(2,n);
cout <<sum;
}