![](/img/trans.png)
[英]Is it possible to create a pow(double a, double b) function in C without assembly?
[英]Create a function that return the pow b^e
我必須創建一個返回 b^e 值的函數。 這就是我所做的:
#include<stdio.h>
#include<math.h>
int funzione_potenza (int b, int e);
int main ()
{
int b, e, potenza;
printf("Inserisci la base: ");
scanf("%d",&b);
printf("Inserisci l'esponente: ");
scanf("%d",&e);
printf("La potenza e' %d",potenza);
return 0;
}
int funzione_potenza (int b, int e)
{
int potenza;
potenza = pow(b,e);
return potenza;
}
當我運行它時,它顯示功率的錯誤值(例如 5343123) 有什么問題?
您不需要函數來調用內置的 pow 函數。 如果您正在嘗試編寫自己的函數,請嘗試使用循環或遞歸構建解決方案。
假設您可以自由使用數學庫,除非數字適合“int”,否則該方法將返回正確答案。 否則,考慮對更大的數字使用“long long int”。
如果您不被允許使用數學庫,這里是一個正確的實現:
long long int power(int b, int e){
if(e==0){
return 1;
}
else if(e%2==1){
long long int temp = power(b,e/2);
return temp*temp*b;
}
else{
long long int temp = power(b,e/2);
return temp*temp;
}
}
有兩個問題:
首先,你得到了一個垃圾值,因為你從不調用funzione_potenza
函數。
int main()
{
int b, e, potenza;
printf("Inserisci la base: ");
scanf("%d", &b);
printf("Inserisci l'esponente: ");
scanf("%d", &e);
potenza = funzione_potenza(b, e); // <<<<<<<<<< insert this line
printf("La potenza e' %d", potenza);
return 0;
}
其次,您甚至不需要funzione_potenza
這只是pow
的包裝器,您可以直接調用pow
:
...
scanf("%d", &e);
potenza = pow(b, e);
printf("La potenza e' %d", potenza);
...
您可以在不使用“pow”的情況下實現冪函數“pow”-function內置函數以及下面的代碼。
#include <stdio.h>
//function prototype
int funzione_potenza (int b, int e);
int main ()
{
int b, e, potenza;
printf("Inserisci la base: ");
scanf("%d",&b);
printf("Inserisci l'esponente: ");
scanf("%d",&e);
potenza = funzione_potenza (b,e);
printf("La potenza e' %d",potenza);
return 0;
}
int funzione_potenza (int b, int e)
{
//local variables
int i, potenza = b; //initialize potenza with b
for (i = 0; i < e; i++ )
{
potenza = potenza * e; //multiply n-number of times to get the power
}
return potenza;
}
我的目的是展示你可以意識到這一點的方式,但這基本上是在重新發明輪子,所以不推薦。 在這里,我展示了如何嘗試編寫冪函數的粗略想法。
實現這一點的另一種方法是
int mpow(int b, int e) {
if (e <= -1) {
fprintf(stderr, "mpow:(b: integer, e:non-negative integer )");
exit(1);
}
if (e == 0) return 1;
if (b == 0) return 0;
int ans = 1;
for (int i = 1; i <= e; i++) {
if (!checkIfOverflown(ans, b)) ans = ans * b;
else {
fprintf(stderr, "%s\n", "overflow in multiplication");
exit(1);
}
}
return ans;
}
當pow
返回double
您不應該將其轉換為整數(為什么要失去精度)。
為什么將pow
包裝在函數中? 您可以直接使用它。
這個函數是正確的,只要整數不會因為溢出東西而弄亂它。 對於b
小值, e
它有效。
還有一種更簡單、更有效的方法是
int mpow(int b, int e) {
int res = 1, flag = 0;
if (e <= -1) {
fprintf(stderr, "mpow:(b: integer, e:non-negative integer )");
exit(1);
}
while (e > 0) {
if (e % 2 == 1) {
if (!checkIfOverflown(res, b))
res = (res * b);
else {
flag = 1;
break;
}
}
if (!checkIfOverflown(b, b))
b = (b * b);
else {
flag = 1;
break;
}
e /= 2;
}
if( flag ){
fprintf(stderr, "%s\n", "overflow in multiplication");
exit(1);
}
return res;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.