Pow c ошибки

lavengerl

0 / 0 / 1

Регистрация: 18.09.2011

Сообщений: 77

1

12.11.2011, 20:08. Показов 8130. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <conio.h>
#include <math.h>
using namespace std;
 
class Triangle
 
{
public:
    int a,b,c;
    double al,bt,gm;
 
    void display(void);
Triangle(int _a, int _b, int _c) //конструоктор
    {
        a=_a;
        b=_b;
        c=_c;
    }
~Triangle();
};
void Triangle::display(void)
{
 
        al=acos((pow(b,2)+pow(c,2)-pow(a,2))/2*b*c);
        cout<<"alfa="<<this->al;
}
 
void main()
{
    Triangle obj(2,3,4);
 
    getch();
    system("cls");
}

ошибки:
3 таких ошибки(на каждый пов):
Ошибка 1 error C2668: pow: неоднозначный вызов перегруженной функции c:documents and settingsadmin.skerskijмои документыvisual studio 2010projectslaba3laba31.cpp 25 1 laba3

и 3 таких (на каждый пов):
4 IntelliSense: существует более одного экземпляра перегруженная функция «pow», соответствующего списку аргументов: c:documents and settingsadmin.skerskijмои документыvisual studio 2010projectslaba3laba31.cpp 32 12 laba3

можно ли как-то справится без перегрузки?



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

12.11.2011, 20:08

6

Jupiter

Каратель

Эксперт С++

6608 / 4027 / 401

Регистрация: 26.03.2010

Сообщений: 9,273

Записей в блоге: 1

12.11.2011, 20:12

2

C++
1
pow(b, 2.0)

в других аналогично



2



В вечном поиске…

275 / 235 / 30

Регистрация: 05.04.2011

Сообщений: 645

12.11.2011, 20:14

3

А зачем юзать «pow», когда числа можно просто умножить друг на друга?

Добавлено через 1 минуту

Не по теме:

Jupiter, модером стал, поздравляю!:bravo:



1



lavengerl

0 / 0 / 1

Регистрация: 18.09.2011

Сообщений: 77

12.11.2011, 20:24

 [ТС]

4

Цитата
Сообщение от Nursik77
Посмотреть сообщение

А зачем юзать «pow», когда числа можно просто умножить друг на друга?

Добавлено через 1 минуту

Не по теме:

Jupiter, модером стал, поздравляю!:bravo:

зачем «просто множить числа» если по моей задаче необходимо теоремой коссинусов найти угол, а в ней нужно находить квадраты сторон.

Добавлено через 1 минуту

Цитата
Сообщение от Jupiter
Посмотреть сообщение

C++
1
pow(b, 2.0)

в других аналогично

спасибо, работает. никогда бы сам не додумался)



0



Nursik77

В вечном поиске…

275 / 235 / 30

Регистрация: 05.04.2011

Сообщений: 645

12.11.2011, 20:26

5

lavengerl, я имел ввиду:

C++
1
2
3
4
5
6
7
8
...
void Triangle::display(void)
{
 
                al=acos(b*b+c*c-a*a)/2*b*c);
                cout<<"alfa="<<this->al;
}
...



0



Jupiter

Каратель

Эксперт С++

6608 / 4027 / 401

Регистрация: 26.03.2010

Сообщений: 9,273

Записей в блоге: 1

12.11.2011, 20:27

6

lavengerl, Nursik77 прав!
да и посудите сами

C++
1
2
pow(b,2) //8 символов против
b * b //3-х

к тому же у вас ошибка в формуле
окончательный вариант вот

C++
1
al = acos((b * b + c * c - a * a) / (2 * b * c));



2



lavengerl

0 / 0 / 1

Регистрация: 18.09.2011

Сообщений: 77

12.11.2011, 21:05

 [ТС]

7

Цитата
Сообщение от Jupiter
Посмотреть сообщение

lavengerl, Nursik77 прав!
да и сами посудите

C++
1
2
pow(b,2) //8 символов против
b * b //3-х

к тому же у вас ошибка в формуле
окончательный вариант вот

C++
1
al = acos((b * b + c * c - a * a) / (2 * b * c));

спасибо



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

12.11.2011, 21:05

Помогаю со студенческими работами здесь

при вызове функции pow() выдаёт ошибку: test.cpp:(.text+0x59b): undefined reference to `pow’
В чём дело?

Добавлено через 1 минуту
ps. Заголовок math.h подключен.

pow
Есть выражение y=pow(g,x)%p

y,g,x,p- int

Ошибка 1 error C2296: %: недопустимо, левый операнд…

pow
ребята, а можно как нибудь сделать чтобы pow(a,b) возвращал не double , а int?

Pow (n, 0)
#include &lt;stdio.h&gt;
#include &lt;conio.h&gt;
#include &lt;math.h&gt;

int main() {

printf(&quot;%d&quot;, pow (…

pow(5, 2) == 24?
Недавно скачал новый Code::Blocks и при выполнении этой программы

#include &lt;iostream&gt;
using…

Функция pow
#include &lt;iostream&gt;
#include &lt;cmath&gt;

using namespace::std;

double pow(double x, double y)…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

7

There is no way to use the ^ (Bitwise XOR) operator to calculate the power of a number.
Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.

1. Using a while loop.

#include <stdio.h>

int main() {

    int base, expo;
    long long result = 1;

    printf("Enter a base no.: ");
    scanf("%d", &base);

    printf("Enter an exponent: ");
    scanf("%d", &expo);

    while (expo != 0) {
        result *= base;
        --expo;
    }

    printf("Answer = %lld", result);
    return 0;
}    
             

2. Using the pow() function

#include <math.h>
#include <stdio.h>

int main() {

    double base, exp, result;

    printf("Enter a base number: ");
    scanf("%lf", &base);

    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculate the power of our input numbers
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);

    return 0;
}
     

The error “undefined reference to ‘pow’” can occur when trying to write a c/c++ program. So what exactly is “pow”? The “pow” is a function used in c or c++ which returns the power of a number. While using the pow function, you may encounter the error like “undefined reference to pow”. If you are looking for the solutions to this error, we have compiled this guide to serve the purpose.

What leads to “undefined reference to pow”?

It is a rather small error hence its reasons are very simple and they can be understood easily. This section will tell you some common reasons that invoke this error.

Reason 1: The Header file <math.h> is not imported

The first reason that you might be getting this error is that you have not imported the header file named <math.h> in your code. The function “pow” is part of this header file, therefore the absence of this header file will give you an “undefined” error.

Reason 2: The Argument (-lm) is not passed while compiling

Second most common reason for this issue occurs when compiling this code. While compiling the code, if the argument (-lm) is not passed, the program will return the “undefined reference to pow” error.

Keeping in view the reasons mentioned above, we have provided a distinctive solution to each reason.

Solution 1: Import the <math.h> header file

The <math.h> file should be imported in the program where the pow function is being used. Enter this header into your C program file using “#include”:

#include<math.h>

See the example below on how to insert the header:

Solution 2: Pass the (-lm) argument while compiling

To compile the program it is extremely important to make sure that we follow the correct syntax as well as include the (-lm) argument so that our code is linked with the maths library “libm.a”. Let us see how to write a command that will compile the file:

$ gcc -o example example.c -lm

The following is an example of the syntax to compile and run the c code:

Conclusion

The undefined reference to pow error is invoked if we miss the <math.h> header file or the program is not compiled correctly. To avoid this error, make sure you have included the header file and it is recommended to compile the program using the GCC with -lm argument. In this post, you have learned to fix the undefined reference to pow” error.

Undefined reference to ‘pow’ error is common to occur when writing code in C or C++. The pow function in C/C++ is useful for returning the power of a given number.Undefined reference to pow

To make your time valuable, we duplicated the codes in which error occurs commonly. In this post, you will learn what causes the error and how to fix it.

Contents

  • Why Am I Getting Indefined Reference to Pow’ Error?
    • – Failure to Import math.h Header File
    • – Failure To Pass Argument (-lm) When Compiling
  • How To Solve the Undefined Reference Error
    • – Following The Right Syntax
    • – Import the <math.h> Header File
    • – When Compiling Pass the (-lm) Argument
  • FAQs
    • – What Is an Undefined Reference in C Programming Language?
    • – What Types of Data Does Pow() Return?
  • Conclusion

Why Am I Getting Indefined Reference to Pow’ Error?

The reason you are getting the undefined reference to pow’ makefile error is that your program is unable to find the definition of pow(). Moreover, it happens when your compiler is unable to locate the necessary header file that defines the pow() function.

That said, there are various causes that may trigger the undefined reference to ‘pow’ cmake error. This problem is inevitable even if you declare the math.h in your program on Linux. Although doing so declares math.h, it does not define pow. As a result, the compiler will throw the error since it is unable to find the definition.

The main reason pow() is not working in your C program is that you forgot to include the math library. Also, the reason could be, by default, the math library is not connected to your binary. Keep reading to find out how you can deal with this error even in a Linux environment.

Below is a quick breakdown of the causes of the undefined reference to function in C error.

As pointed out, you will trigger the undefined reference to ‘sqrt’ if your program does not import the math.h header file while you use the pow() function in C. Pow in C is part of the math.h header file. Therefore, if you forget to include the header file you will trigger this error or one of its variation such as undefined reference to ‘main’.Undefined reference to pow causes

Suppose you wish to compute 9 to the power of 10 in C but you forget to include the math.h header file, then your code would look as follows:

#include <stdio.h>

int main()

{

int res = pow(9,10);

printf(“%dn”, res);

return 0;

}

Running this code will generate the error in question.

– Failure To Pass Argument (-lm) When Compiling

The second most common cause of the error takes place when compiling your code. As you compile your program, the failure to pass the argument (-lm) will result in the “undefined reference to pow” issue.

There could be several reasons that explain why you can’t pass an argument (-lm) which we have discussed below.

You can solve the undefined reference error by following the right syntax and importing the <math.h> header file. There could be other small reasons like not passing the required argument while compiling the program in C, C++, or Linux.

By following the same methods listed below, you can also tackle with variations of error like undefined reference to max.

– Following The Right Syntax

In C/C++ pow is a predefined function within the math.h header file. The function is useful for calculating the power of a certain number. For example, 7^4 in programming will be an expression that raises 7 to the 4th power.

This is where pow() comes in C. To be in a position to use the function, make sure you include the math.h header file.

The syntax for the ‘pow’ function takes the following form:

int pow( int base_number, int power_int)

Where the base_number is the input number you want to calculate its power with power_number indicating the power for the input value.

The function provides an easy way of finding the power of a number. Although you can write a function to calculate the power of a number, there is no need to do this since pow() already exists.

Suppose you want to calculate the square of 144 in C. You can accomplish this as follows:

#include <stdio.h>

#include <math.h>

int main()

{

int res = pow(144,2);

printf(“%dn”, res);

return 0;

}

Notice that you are printing the output of pow(144,2). Also, it is worth pointing out that math.h has been imported at the top of the program. So, if you run the program, the output will be 20736.

As you use the pow() in your program, make sure you import the <math.h> header file. To add it to your program in C, you should use the “#include” tag. It should look as follows:Undefined reference to pow fixes

Now, suppose you still want to calculate the value of a number a user enters raised to the power of their choosing.

To do this, you need to include the math header file. In this case, to accomplish this you need a program that looks as follows:

#include <stdio.h>

#include <math.h>

int main()

{

double base_value, res, power;

printf(“Provide your base number: “);

scanf(“%lf”, &base_value);

printf(“Provide the exponent: “);

scanf(“%lf”, &power);

res = pow(base_value,power);

printf(“%.1lf^%.1lf = %.2lf”, base_value, power, res);

return 0;

}

The output, in this case, will depend on the input from the user.

– When Compiling Pass the (-lm) Argument

As you compile your program in C, make sure you follow the right syntax, especially when using the pow(). Keep this in mind, especially when doing this on Linux. Remember to add the (-lm) argument to ensure your code connects to “libm.a” (maths library). Here is how you can write the command to pass (lm) argument and successfully compile your program.

On Linux, when you include the math.h header in the program then you are adding the pow() function declaration and not its definition. The libm.a library file holds the detailed definition for the function. A library is a collection of various object files.

The path to libm.a file on Linux is ‘/usr/lib/libm.a’. Therefore, you must pass this path to the library location with the argument as you compile your program on the terminal. Therefore, you have to link your C program with the library to make sure calls to functions such as pow() are solved. You can pass the path to the library in two ways.

First, you can provide the full path to the library file as follows:

$ gcc -o ExampleProgram ExampleProgram.c /usr/lib/libm.a

Alternatively, you can directly use -lm in the arguments. This will automatically locate the location of the math library. This is the recommended approach to linking library files using arguments. Here is how you can pass the -lm argument.

$ gcc -o ExampleProgram ExampleProgram.c -lm

FAQs

– What Is an Undefined Reference in C Programming Language?

A reference remains undefined in C programming language when a reference to a relocatable object (function, class, variable, etc) does find its definition even after searching all the object files. Also, when you use a shared object to build a dynamic application but you leave an unresolved reference definition.

– What Types of Data Does Pow() Return?

The pow() function will return the base value to the exponent. Both the base value and the power or exponent are in decimal values. This is because the pow() function accepts float, double, and int. It is important to note that function does not always work with integers.

Conclusion

In C, you will trigger this pow() error for various reasons. Here is a recap of what you learned in this post:

  • The error from failure to import the math.h header file
  • Another cause of the error when using pow() is no passing (lm) when compiling
  • One solution to the issue is to import <math.h> header file in your program
  • If running your program on Linux, compile it using GCC which has the lm argument

With this knowledge, you now easily tackle this error whenever it occurs.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

C program undefined reference to pow error

Why this undefined reference to pow error raised in compilation?

When we use the pow function or any other math functions from math header in c program on linux environment (RHEL, Fedora or CentOS), need to use -lm option for compilation.

otherwise you will get undefined reference to pow error, when you compile below program with no -lm option.

#include<stdio.h>                                                              
#include<math.h>                                                                
                                                                                
float PMT (int interest, int loan_amount, int total_months) {                   
 float rate, denominator;                                                       
 rate = (float) interest/100/12;                                                
 denominator = pow((1+rate), total_months)-1;                                   
 return (rate+(rate/denominator))*loan_amount;                                  
}                                                                               
void main()                                                                     
{                                                                               
 int loan_amount, loan_term_years, num_of_emi_per_year;                         
 float rate_of_interest, pmt_value;                                             
                                                                                
 printf("nEnter loan amount: ");                                               
 scanf("%d", &loan_amount);                                                     
                                                                                
 printf("nEnter loan tearm in years: ");                                       
 scanf("%d", &loan_term_years);                                                 
                                                                                
 printf("nEnter number of EMI per year: ");                                    
 scanf("%d", &num_of_emi_per_year);                                             
                                                                                
 printf("nEnter rate of interest: ");                                          
 scanf("%f", &rate_of_interest);                                                
 pmt_value= PMT(rate_of_interest, loan_amount, loan_term_years*num_of_emi_per_year);
 printf("nEMI: %f", pmt_value);                                                
}    

Output:

$ cc emi_calculator.c
/tmp/cc4v5U2R.o: In function `PMT':
emi_calculator.c:(.text+0x5a): undefined reference to `pow'
collect2: error: ld returned 1 exit status

To fix this issue, need to use -lm option in compilation command.

Output:

$ cc emi_calculator.c -lm
$ ./a.out 

Enter loan amount: 396000

Enter loan tearm in years: 4

Enter number of EMI per year: 12

Enter rate of interest: 15

EMI: 11020.946289

C program provides expected output when running a.out file once you compiled the program with -lm option.

If you want different name instead of a.out file, we need to use -o option to create executable file with custom name.

$ cc -o emi emi_calculator.c -lm
$ ./emi
Enter loan amount: 396000

Enter loan tearm in years: 4

Enter number of EMI per year: 12

Enter rate of interest: 15

EMI: 11020.946289

Понравилась статья? Поделить с друзьями:
  • Potplayer сервер перегружен или ошибка ввода адреса
  • Potplayer произошла ошибка во время воспроизведения
  • Potplayer ошибка создания плейлиста
  • Potplayer ошибка при воспроизведении файла
  • Potplayer неизвестная ошибка пожалуйста попробуйте еще раз