c++ - C++ if 语句不打印所需的输出
问题描述
问题在于 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;
}
解决方案
你的逻辑是错误的(我不得不说有点奇怪)。
如果那input
是不正确的,那么你永远不会达到你的陈述。1
while (sum < input)
if (input == 1)
推荐阅读
- c - 分段错误:11 在 C 中使用 pthread 库的多线程程序中
- angular - 带有变量的Angular 6组件测试到HTML
- javascript - Chrome 扩展不尊重 browser_specific_settings
- powershell - 格式颁发者输出
- windows - 读取键和更新值的批处理脚本
- java - maven.springframework.org/release 被缓存在本地存储库中
- angular - 如何在 Angular 中设置数组形式?
- python - seaborn 轴范围不适合 Python 中的数据范围
- c++ - 如何根据模板参数生成代码?
- python - 使用 tensorflow-gpu 后端导入 Keras 时出错(找不到 libcublas.so.10.0)