Power calculation

Asked

Viewed 88 times

-3

Make a program that receives a 200 position vector (int)

Next create a function that returns the power squared of each element of the vector.

The main program should display all results on the screen.

#include <stdlib.h>
#include <time.h>
#include <windows.h>
#include <cstdio>
using namespace std; 

int x, base, resp = 0, vet[200];

int calc(int base, int resp){

    resp = (base * base); 

    return resp;    
}
main(){   
    setlocale(LC_ALL, "Portuguese") ;

    for (x = 0; x < 200; x++) {
        vet[x] = x;
        cout << endl << "Posição " << x + 1 << " : " << vet[x];
    }

    for (x = 0; x < 200; x++) {
        cout << endl;
        cout << endl << vet[x] << "² =  " << calc(vet[x], resp);
    }

    getch();
}

Where is the error? It does not rotate.

  • The main prototype is correct ? -- int main( int argc, char ** argv )

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

  • If you want you can signal that the question is anonymous but do not edit it so that without context or radically.

2 answers

1

The code is very confusing, there are things that are not quite C++, but for exercise goes. I think this function calc() is unnecessary in this case, but the biggest problem I see is not being using the power function (pow()), which seems to be the goal. Even the algorithm is weird and can do better.

#include <iostream>
#include <cmath>
using namespace std; 

int calc(int base) {
    return pow(base, 2);
}

int main() {   
    int vet[200];
    for (int x = 0; x < 200; x++) {
        vet[x] = x;
        cout << endl << "Posição " << x + 1 << " : " << vet[x];
    }
    for (int x = 0; x < 200; x++) cout << endl << vet[x] << "² =  " << calc(vet[x]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

0

1) You are working with global variables, this choice is not very indicated. Generally the use of global variables are to define, for example float pi = 3.1415;, this value will not be changed, in small codes the use of global variables may not be noticed but, as the code grows its use begins to show its problems. For example, when working with microcontrollers and programming embedded systems this type of definition is common, as it avoids wasting memory.

2)You only need the base

int pot2(int base){
   return base*base;
}

3) If you choose the function of the cmath library you can perform as has already been said here in this discussion by Maniero

Browser other questions tagged

You are not signed in. Login or sign up in order to post.