Potenze

Stato
Discussione chiusa ad ulteriori risposte.
Ok allora beccati questo :D
Codice:
#include<iostream>

using namespace std;

float powa(int base, int esp){
    if(esp==0) return 1;
    if(esp==1) return base;
    return base*powa(base, esp-1);
}

int main()
{
    int base, exp;
    float ris;
    cout << "Inserisci la base"<<endl;
    cin >> base;
    cout << "Inserisci l'esponente"<<endl;
    cin >> exp;
    if(exp<0)
    	ris = 1/powa(base, exp-(exp*2));
    else
    	ris = powa(base, exp);
    cout << "La potenza di " << base << " elevato alla " << exp << " è "
         << ris << endl;
    #if defined(WIN32)
        system("pause");
    #endif
    return 0;
}
 
Ciao...

Scusate l'intromissione ma la domenica è l'unico giorno che ho per studiacchiare e tra le altre cose faccio qualche esercizio di programmazione per non perdere la mano...

[C]
Codice:
//Programma che calcola le potenze

#include <iostream>
using namespace std;

double power(int, int);

int main () {
	
	int base, esp;
	
	cout << "Inserire la base: \n";
	cin >> base;
	cout << "\nInserire l'esponente: \n";
    cin >> esp;
	
	cout << "\n\n   --- IL RISULTATO E': " << power(base, esp);
	
	return 0;
}

double power(int base, int esp){
    int i;
	float flag = 1;
	
	if (esp == 0) return 1;
	
	else if(esp > 0){		
		while(i < esp){
			flag *= base; 
			i++;
		}
		return flag;
	} 
	else { 
		while(i < -esp){
			flag *= base;
			i++;
		}
		return 1/flag;
	}
}

Che ne pensate?
 
visto ormai che è stato duppato,
posto il mio in ruby
Codice:
puts "Elevamento a potenza:           [base^esp]";
str = gets.chomp
str = str.split("^")
if str.size < 2
    exit
end
base = str[0]
esp = str[1]
if esp == 0
    puts "1"
    exit
end
x = 0

while x <= esp
     x *= x
end
puts x


esempio:
Codice:
ruby power.rb
Elevamento a potenza:           [base^esp]
2^2
4
 
Codice:
public class Main {
    static int Potenza(int base, int esponente)  {
        for (int i = 1; i < esponente; i++ ) {
            base *= base;
        }
    return (base);
    }

    public static void main(String[] args) {
       System.out.println(Potenza(3,2));
    }

}
 
[Perl] code di merd*.
Codice:
#!/usr/bin/perl  

sub my_pow($base, $esp) {
            for ($i= 0;$i <= $esp; $i++){
                       $ris = $base* $esp * $esp;
					  }
					  return $ris;
					   }
 $base = shift;
 $esp =  shift;
 $ris =&my_pow($base, $esp);
 print "il risultato e' $ris";

Ed in C:

Codice:
#include <stdio.h>


int main(){

  int i = 1, x, y, power = 1;
  printf("inserisci la base:\n");
  
  scanf("%d", &y); 
  printf("inserisci l'esponente:\n");
  scanf("%d", &x); //esponente
  
  while( i <= x){
         
         power *= y;
         
         ++i;
         }
         printf( "Power of %d is %d\n", y, power);
         
         getchar();
         getchar();
          return 0;
          }

Senza funzione perchè mi rompevo a scriverla :- ).
 
Stato
Discussione chiusa ad ulteriori risposte.