M
M
Maxim Rudnev2015-11-02 01:18:00
Programming
Maxim Rudnev, 2015-11-02 01:18:00

Question about for loop c++?

#include<iostream>
#include<conio.h>		
#include<cmath>
using namespace std;
using std::cout;
using std::endl;
using std::cin;
using std::ios_base;

int main()
{


  int a, b, r=1;
  cout << "a-chislo, b-kol-vo ciklov" << endl;

  if (!(cin >> a && cin >> b))

    cout << "error" << endl;
  else if (a < 0 && b < 0)
    cout << "error" << endl;
  else



    for (int i = 1; i <= b; i = i + 1)
      r = r*a;
    cout << "result: "<<r << endl;
    _getch();
  return 0;
}
Raising a number to a power using a loop. At random it was possible to make a working code. Tyk was in the variable "r" and assigning the value "=1" to it, only then it worked. But the logic of this expression r=r*a, if r=1, is not fully understood. Why does the cycle go, only in this case, and not, for example, in such r=2*a. Otherwise, the value of the first repetition is immediately displayed, and in the original I get the degree of the number with all repetitions. If you write r=b*a, the result will be without repetitions, and r=r*a already with repetitions according to the for condition. Help understand

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Rudnev, 2015-11-02
@stigmt

I found the answer to my question here skeletoncoder.blogspot.ru/2006/09/java-tutorials-i...

O
Oleg Tsilyurik, 2015-11-02
@Olej

Help understand

It is impossible to understand this explanation of the question.
And raising a number to a power is better like this (this is just for fun):
double power( double a, int n, int& m ) {
   assert( n > 0 || ( a != 0.0 || n != 0 ) );
   switch( n ) {
      case 0:
         return 1;
      case 1:
         return a;
      default : {
         double a2 = power( a, n / 2, m );
         if( n & 1 ) {
            m += 2;
            return a * a2 * a2;
         }
         else {
            m++;
            return a2 * a2;
         }
      }
   }
}

int main() {
   double e, r;
   int n, m;
   while( true ) {
      cout << "что возводить? : ";
      cin >> e;
      cout << "в какую степень? : ";
      cin >> n;
      m = 0;
      r = power( e, n, m );
      cout << e << "**" << n << "=" << r << ", число умножений " << m << endl;
   }
   return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question