Error pow was not declared in this scope

error in my code!!

hey all :)))
im getting error on my code :(

int main()
{

string inp;
int dec=0; //store
char base;
cout << «input number: «;
cin >> inp;
cout << «input base: «;
cin >> base;
L17 for (int i = inp.length ()-1; j = 0; ++j) dec += (inp[i]-48) * pow ((float) base-48,j);
cout << «your number in base 10 is: » << dec << endl;
L19 system («pause»);
return 0;

LINE 17 ERROR:
-ERROR: ‘j’ was not declared in this scope
-ERROR: ‘pow’ cannot be used as a function

LINE 19:
-ERROR: ‘system’ was not declared in this scope

*using codeblocks

tyy!! :)))

I think you need to include the math library as well as declare variable j. System («pause») is not necessary. Whatever book is telling you to use it, throw it out.

I edited it and it now runs fine on my machine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	
	string inp;
	int dec=0; //store
	char base;
	cout << "input number: ";
	cin >> inp;
	cout << "input base: ";
	cin >> base;
	
	for (int i = inp.length ()-1; int j = 0; ++j) dec += (inp[i]-48) * pow ((float) base-48,j);
	cout << "your number in base 10 is: " << dec << endl;

	return 0;
}

This needed to be added:

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

for (int i = inp.length ()-1; int j = 0; ++j) dec += (inp[i]-48) * pow ((float) base-48,j);

Last edited on

-ERROR: ‘j’ was not declared in this scope

Well, here you have for (int i = inp.length ()-1; .... Did you mean int j = inp.length()-1? Also, this j = 0; will make it so that your loop will never execute (it will evaluate to zero which is false). I don’t know exactly what you’re trying to do so I can’t help you here, though you will have to change this terminating condition.

-ERROR: ‘pow’ cannot be used as a function

Yes it can :s Did you #include <cmath> ?

-ERROR: ‘system’ was not declared in this scope

You need to #include <cstdlib> to use the system function (but don’t)

theres no way I can use this logic as a string?? (its for class and we havent leared cmath)

pow is declared in <cmath> or <math.h>

You need to re-examine your for loop though. Right now it doesn’t execute. You should start i at inp.length()-1 and j at zero. You should terminate when i becomes less than zero, and you should be incrementing j and decrementing i.

Im trying to
input number
input base
print DECIMAL

not working!!

Can we see the new code?

Another error I see is this pow ((float) base-48,j). If base is eight (octal), for example, then you’ll be adding the current digit times -40j.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{

string inp;
int j;
int dec=0; //store
char base;
cout << «input number: «;
cin >> inp;
cout << «input base: «;
cin >> base;
for (int i = inp.length ()-1; j == 0; ++j) dec += (inp[i]-48) * pow ((float) base-48,j);
cout << «your number in base 10 is: » << dec << endl;

return 0;
}

this when I input..prints 0

j == 0;

At this point, j is uninitialized. If j just happens to be zero, then this will be an infinite loop. Your loop shouldn’t terminate when j != 0 (which is what it currently says). I think what you want to do is start i at inp.length ()-1 (last character) and move i to (first character). As such, you should terminate the loop when i becomes less than zero.

pow ((float) base-48,j)

I went over this in my last post but I was wrong. base-48 works because base is a char, though why don’t you just declare base as an int so you don’t have to subtract 48.

(inp[i]-48)

On the subject of 48, it’s a magic number. You should do inp[i] - '0' instead. This goes the same for above, pow ((float) base - '0',j) though like I said you should just make base an int

Your main issue is with your for loop header. This is what you should be doing:

shacktar wrote:
You should start i at inp.length()-1 and j at zero. You should terminate when i becomes less than zero, and you should be incrementing j and decrementing i.

If you use a for loop, then you will be initializing i and j as well as incrementing j and decrementing i. This wouldn’t follow the basic for(T i = 0; (some condition); i++) structure. You may want to implement the above using a while loop instead if you can wrap your head around it better.

Topic archived. No new replies allowed.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    int e=0;
    int b=0;
    cout<<"Enter Exponent";
    cin>>e;
    cout<<"Enter Base";
    cin>>b;
    pow(e, b);
    cout<<"Power:"<<e;
    return 0;
}

void pow(int e, int b)
{
  int t=1;
  while(b==t)
  {
    e=e*b;
    t++;
  }
}

ulaga.cpp|29|error: ‘pow’ was not declared in this scope

Can any one explain why this error occurred?


The C++ compiler parses through your code file sequentially in order. i.e. line 1 then line 2 then line 3… and so on. So by the time the compiler comes to the function call statement pow(e, b); in your main() function, it hasn’t yet reached the definition of the function void pow(int e, int b) below the main() function and therefore gives you the error. There are two ways to solve this.

1) Move the definition of void pow(int e, int b) (and any other function that you plan to call from main()) above the main() function itself. This way the compiler has already parsed and is aware of your function before it reaches the pow(e, b); line in your main().

2) The other way is to use a forward declaration. This means adding the line void pow(int e, int b); before the main() function. This tells the compiler that the function given by the forward declaration (in this case void pow(int e, int b)) is defined in this code file but may be called before the definition code of the function in the file. This is a better method as you may have multiple functions in your file calling one another in different order and it may not be easy to rearrange their definitions to appear before they are called in a file. Here’s a good read on Forward Declaration

You may also want to pass parameters by reference to your function to get the correct result. i.e. use void pow(int& e, int& b). This will cause the values modified in your pow() function to actually be applied to integers e and b and not just to their copies which will be thrown away after pow() is done executing. This link about passing arguments by reference in functions is pretty good at explaining this.

Синтаксические ошибки

Первые ошибки, которые определяются отладчиком – это синтаксические ошибки. Их же легче всего исправить. Неправильный синтаксис в Arduino IDE выделяется строкой, в которой допущена неточность. Нужно разобраться – это ошибка в написании служебного слова, случайно удалена важная функция, не хватает закрывающейся скобки или неправильно отделены комментарии.

Для определения ошибки внимательно просмотрите строку-подсказку и внесите необходимые изменения. Ниже мы приведем примеры наиболее часто встречающихся синтаксических ошибок компиляции кода:

  • Ошибка “expected initializer before ‘}’ token” говорит о том, что случайно удалена или не открыта фигурная скобка.
  • Ошибка “a function-definition is not allowed here before ‘{‘ token” – аналогичная предыдущей и указывает на отсутствие открывающейся скобки, например, открывающих скобок в скетче только 11, а закрывающих 12.
  • Уведомление об ошибке “undefined reference to “setup” получите в случае переименования или удаления функции “setup”.
  • Ошибка “undefined reference to “loop” – возникает в случае удаления функции loop. Без команд этой функции компилятор запустить программу не сможет. Для устранения надо вернуть каждую из команд на нужное место в скетче.
  • Ошибка “… was not declared in this scope” обозначает, что в программном коде обнаружены слова, которые написаны с ошибкой (например, которые обозначают какую-то функцию) или найдены необъявленные переменные, методы. Подобная ошибка возникает также в случае случайного удаления значка комментариев и текст, который не должен восприниматься как программа, читается IDE.

Ошибки компиляции и их решения, для плат Arduino, синтаксические ошибки картинка

Ошибки библиотек

Большое количество ошибок возникает на уровне подключения библиотек или неправильного их функционирования. Наиболее известные:

  • “fatal error: … No such file or directory”. Такое сообщение вы получите, если необходимую в скетче библиотеку вы не записали в папку libraries. Сообщение об ошибке в одном из подключенных файлов может означать, что вы используете библиотеку с ошибками или библиотеки не совместимы. Решение – обратиться к разработчику библиотеки или еще раз проверить правильность написанной вами структуры.
  • “redefinition of void setup” – сообщение возникает, если автор библиотеки объявил функции, которые используются и в вашем коде. Чтобы исправить – переименуйте свои методы или в библиотеке.

Ошибки компилятора

Нестабильность в работе самого компилятора тоже могут возникать при отладке программы. Вариантов выхода из данной ситуации может быть несколько, например, установить последнюю версию компилятора. Иногда решением может быть наоборот, возвращение до более старой версии. Тогда используемая библиотека может работать корректно.

Ошибки компиляции при работе с разными платами — Uno, Mega и Nano

В Arduino можно писать программы под разные варианты микроконтроллеров. По умолчанию в меню выбрана плата Arduino/Genuino Uno. Если забудете о том что нужно указать нужную плату – в вашем коде будут ссылки на методы или переменные, не описанные в конфигурации “по умолчанию”.

Вы получите ошибку при компиляции “programmer is not responding”. Чтобы исправить ее – проверьте правильность написания кода в части выбора портов и вида платы. Для этого в Ардуино IDE в меню «Сервис» выберите плату. Аналогично укажите порт в меню “Сервис” – пункт «Последовательный порт».

Ошибка exit status 1

В среде разработки такое сообщение можно увидеть во многих случаях. И хотя в документации данная ошибка указывается как причина невозможности запуска IDE Аrduino в нужной конфигурации, на самом деле причины могут быть и другие. Для того, чтобы найти место, где скрывается эта ошибка можно “перелопатить” действительно много. Но все же стоит сначала проверить разрядность системы и доступные библиотеки.

Ошибки компиляции и их решения, для плат Arduino, Ошибка exit status 1

Обновления и исправления касательно версий инструкции и ПО

Понравилась статья? Поделить с друзьями:
  • Error potential leak of memory pointed to by
  • Error posting data please reload page
  • Error postcss received undefined instead of css string
  • Error postcss plugin tailwindcss requires postcss 8
  • Error post loading model hlmv