问题在于while循环内的if语句。它没有打印所需的输出。 else if语句和else语句似乎正常工作 感谢您的帮助
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
while (sum < input) {
// This is the if statement giving me problems
if (input == 1) {
exponent += 1;
sum = 3;
}
// This else if statement seems to work fine
else if (input == 3) {
exponent += 2;
sum = 9;
}
else {
exponent++;
sum *= base;
}
}
// Print output
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
答案 0 :(得分:3)
您的逻辑是错误的(我不得不说有点奇怪)。
如果input
为1
,则while (sum < input)
不正确,因此您永远不会到达if (input == 1)
语句。
答案 1 :(得分:1)
纠正了我的错误。我只是将if和else if语句移到了循环之外
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
if (input == 1) {
exponent += 1;
sum = 3;
}
else if (input == 3) {
exponent += 2;
sum = 9;
}
while (sum < input) {
exponent++;
sum *= base;
}
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
答案 2 :(得分:1)
如果我从评论中理解了客观权利,则不需要if
条件。只需替换条件并简化while
循环即可,如下所示:
while (sum <= input) {
exponent++;
sum *= base;
}
答案 3 :(得分:0)
编写一个C ++程序,要求用户输入整数。该程序 查找并显示比输入数字大3的第一幂 使用while
您可能应该计算答案而不是循环。
#include <iostream>
#include <cmath>
int main() {
int input;
std::cout << "input: ";
std::cin >> input;
int x = 0;
/*
3^x == input
ln(3^x) == ln(input)
x*ln(3) == ln(input)
x == ln(input)/ln(3)
*/
// calculate x = ln(input)/ln(3), round down and add 1
if(input > 0) x = std::floor(std::log(input) / std::log(3.)) + 1.;
std::cout << "answer: 3^" << x << " == " << std::pow(3, x) << "\n";
}