C++ Code Without chaning any code below, could anyone help me to get the second
ID: 3809250 • Letter: C
Question
C++ Code
Without chaning any code below, could anyone help me to get the second line?
Ex1)
Please enter a number from 3 to 100: 6
2, 4 (<--------This is what I need - there should be no comma at the end!)
The answer is 4
Please enter a number from 3 to 100: 100
2, 4, 8, 16, 32, 64 (<-------this is what I need - no comma at the end!)
The answer is 64
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int powerOfTwo(int num);
int main () {
int num;
int result;
int i=1;
cout<<"Please enter a number from 3 to 100: ";
cin>>num;
cout << num << endl;
if ((num < 3) || (num > 100))
cout << "Please follow the directions!" << endl;
else {
int pow;
pow = powerOfTwo(num);
cout << " The answer is ";
cout << pow;
cout << endl;
}
}
int powerOfTwo(int num) {
int N = num;
int v = 1;
while (v <= N/2)
v *= 2;
cout<<v<<","; (Somebody gave this code- but it ends up with "comma"- anybody knows who to fix it? )
return v;
}
Explanation / Answer
YOU HAVE MISSED A BRACKET WHICH I HAVE POINTED IN THE CODE BELOW.
NEVER EVER MISS BRACKETS, IT BECOMES DIFFICULT TO UNDERSTAND BLOCKS.
ALSO FIXED THE "," PART.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int powerOfTwo(int num);
int main () {
int num;
int result;
int i=1;
cout<<"Please enter a number from 3 to 100: ";
cin>>num;
cout << " You have entered "<<num << endl;
if ((num < 3) || (num > 100))
cout << "Please follow the directions!" << endl;
else {
int pow;
pow = powerOfTwo(num);
cout << " The answer is ";
cout << pow;
cout << endl;
}
}
int powerOfTwo(int num) {
int N = num;
int v = 1;
while (v <= N/2){ //you missed this bracket
v *= 2;
cout<<v<<",";
} //you missed this bracket
cout<<" "<<endl; //this will do the trick
return v;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.