+ 1

why does different data type b result in different consequence ?

I am a new C++ learner and write a small code. But I am confused the results are different. for example, N N^2 N^2 ----------------------- 0 0 0 5 24 25 10 99 100 Thank you for your patient. #include <iostream> #include <iomanip> #include <cmath> using namespace std; int Square(int); int Cubic(int); int main() { int i, C; cout << " N N^2 N^2" << endl; cout << "-----------------------" << endl; for (i = 0; i <= 10; i++) { C = 5 * i; cout << setw(6) << C << " " << setw(6) << Square(C) << " " << setw(6) << Cubic(C); cout << endl; } cout << "-----------------------" << endl; return 0; } int Square(int c) { int b; b = pow(c, 2); return b; } int Cubic(int c) { float b; b = pow(c, 2); return b; } N N^2 N^2 ----------------------- 0 0 0 5 24 25 10 99 100 15 224 225 20 399 400 25 624 625 30 899 900 35 1225 1225 40 1599 1600 45 2024 2025 50 2499 2500 -----------------------

25th Nov 2018, 3:56 AM
Lawrence Lin
Lawrence Lin - avatar
3 Respostas
+ 5
I test ran your code in Code Playground, three times, and all the time the outputs of Square and Cubic are the same. Also I am a bit confused why you use a float in Cubic yet you declared it to return int. If you have different outputs on your side then I guess it was probably a side effect of the rounding that took place as you narrow from float → int. A side note, isn't Cubic supposed to return pow(c, 3) instead? Hth, cmiiw
25th Nov 2018, 4:23 AM
Ipang
+ 5
You're welcome, and let's hope someone come in later who can explain the odds, because IIRC Code Playground also uses MinGW, as the server is running Windows server O/S, I could be wrong though : )
25th Nov 2018, 6:45 AM
Ipang
+ 1
I mean when I use int b, for example of 5^2 ,I get 24. But the type of b is float, the answer is 25. The later answer is right. I just dont know the reason. Maybe just rounding. Sorry, I forget mention that I use visual studio code and MinGW. Yes, you are right, the answer is the same bye using Code Playground. Thanks very much.
25th Nov 2018, 5:10 AM
Lawrence Lin
Lawrence Lin - avatar