首页 > 解决方案 > 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;
}

标签: c++if-statement

解决方案


你的逻辑是错误的(我不得不说有点奇怪)。

如果那input是不正确的,那么你永远不会达到你的陈述。1while (sum < input)if (input == 1)


推荐阅读