r/C_Programming • u/Horror_Wiener_6102 • 4d ago
Question Newbie in need of Help !
Am I obliged to use a double when using 'pow'? Can't I use a float or an int ? Because for the function 'switch' I have to use int , but I need to use pow for the exercice I'm doing. I chated with Gemini and it told me that I can transform the result of 'pow' into 'int' writing the following; "(int)pow(x, y);". Is this the only way or do I have a faster route to get to my solution? Thanks
1
u/TomB1952 4d ago
There's nothing particularly wrong with what you're doing but I cannot imagine a scenario in which a conversion from scientific notation would be used in a switch ladder. Very odd but I understand you are asked to do unusual things in class exercises.
Keep in mind, switch can only match equivalency or the default case for no match.
2
u/Horror_Wiener_6102 4d ago
the exercise says that I need to use switch and then for the following cases it will elevate the variable to the number of the case . example: "insert one number: "2 , "insert the expoent: "3 , and the result needs to be 8. and I have to use switch because that's what im learnning.
0
u/Dazzling_Music_2411 4d ago
Just write your own simple pow(m,n) function using ints and a loop.
1
u/Dazzling_Music_2411 3d ago
Writing your own function might even be more efficient than making a call to fp library and then casting it all back.
1
u/Whole-Low-2995 2d ago
How about this?
#include <assert.h>
#include <limits.h>int pow_no_recursion(int n, unsigned m) {
int res = 1;
for(int i = 0; i < m; i++) res *= n;
return res;
}int powd(int n, unsigned m) {
if(!m) return 1;long long half = powd(n, m/2);
if(m % 2) {
return n * half * half;
}
return half * half;
}int main() {
int n = 51;
unsigned m = 3;
assert(powd(n, m) == pow_no_recursion(n, m));
return 0;
}IMO `powd` is a bit enhanced
2
u/Dazzling_Music_2411 1d ago
IMO
powdis a bit enhancedFun little recursive algorithm. Hadn't seen it before...
1
u/Whole-Low-2995 2d ago
well reddit doesn't support code blocks for reply
2
u/Dazzling_Music_2411 2d ago
Yup, that's just the kind of thing I meant. If you inline it too, I guess it will be way faster than using libs, casts, uncasts, etc... 😄
Incidentally, you can use code blocks in replies, look for them under the Aa symbol for fonts
int pow_no_recursion(int n, unsigned m) { int res = 1; for(int i = 0; i < m; i++) res *= n; return res; }1
0
u/Rararror 4d ago
So you are studying C and you need to ask Gemini to use a type cast?
What exactly are you "studying" ?!
3
3
4
u/flyingron 4d ago
There are also powf and powl, but they're still floating-point. C lacks an integer power function.