How can you fix the limits of a program?

0 votes
asked Dec 1 by (120 points)

#include<iostream>

#include<conio.h>

using namespace std;

int main(){

int numero,resultado=0,exponente;

cout<<"Digite un numero: "; cin>>numero;

cout<<"Y su exponente: "; cin>>exponente;

if(numero<0){

getch(); return 0;

}

if(exponente==0){

cout<<"El resultado es 1"<<endl; getch(); return 0;

}

if(exponente==1){

cout<<"El resultado es "<<numero<<endl; getch(); return 0;

}

resultado=numero*numero;

while(exponente>2){

exponente--;

resultado=resultado*numero;

}

if(resultado<0){

resultado*-1;

}

cout<<"El resultado es "<<resultado<<endl;

getch();

return 0;

}

What you saw is my program, and it works! But it has limits, the program breaks off if your numbers are too big. How can you fix this?

2 Answers

0 votes
answered Dec 3 by anonymous
English

You a using int (it is used for small numbers), try to use float, double or long long int

Portuguese:

Voce está usando o tipo int (esse tipo eh usado em variaveis não tão grandes), tente usar o tipo float, double ou long long int

#include <iostream>

#include<conio.h>

using namespace std;

int main(){

long long int numero,resultado=0,exponente;

cout<<"Digite un numero: "; cin>>numero;

cout<<"Y su exponente: "; cin>>exponente;

if(numero<0){

getch(); return 0;

}

if(exponente==0){

cout<<"El resultado es 1"<<endl; getch(); return 0;

}

if(exponente==1){

cout<<"El resultado es "<<numero<<endl; getch(); return 0;

}

resultado=numero*numero;

while(exponente>2){

exponente--;

resultado=resultado*numero;

}

if(resultado<0){

resultado*-1;

}

cout<<"El resultado es "<<resultado<<endl;

getch();

return 0;

}
0 votes
answered Dec 3 by (2,230 points)

Your variables have type of int (integer). This type, as every other type has a range of numbers that it can represent. While this range is quite high for integer, it is not infinite. To be exact the range is -32,768 to 32,767 on 32-bit systems or -2,147,483,648 to 2,147,483,647 on 64-bit system.

What it means is your "resultado" variable gets so big that it can't be displayed correctly anymore. It got out of the range of integer.

You might want to use a type with bigger range, such as double:

double resultado = 0;

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...