C ++ если оператор не печатает желаемый вывод - PullRequest
0 голосов
/ 01 марта 2019

Проблема со статическим элементом if внутри цикла while.Это не печать желаемого результата.Кажется, что оператор 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;
}

Ответы [ 4 ]

0 голосов
/ 01 марта 2019

Напишите программу на C ++, которая запрашивает у пользователя целое число.Программа находит и отображает первую степень на 3 больше, чем введенное число, используя

Вы, вероятно, должны вычислить ответ вместо зацикливания.

#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";
}
0 голосов
/ 01 марта 2019

осознал мою ошибку.я просто переместил оператор 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;
}
0 голосов
/ 01 марта 2019

Если я понял цель прямо из комментариев, if условия не требуются.Просто замените условие и упростите цикл while следующим образом:

  while (sum <= input) {
    exponent++;
    sum *= base;
  }
0 голосов
/ 01 марта 2019

Ваша логика неверна (и я должен сказать, немного странно).

Если input равно 1, то while (sum < input) неверно и поэтому вы никогда не достигнете своего утверждения if (input == 1).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...