I need help optimizing this code to be cleaner, faster, etc...
[edit]
Added a second code at top of the post, need advice for that one too :P. It works great now, it generates the Fibonacci sequence, and any tips on optimization are appreciated.
i dont know nothing about quadratic equation either, so i dont know you use the right function. However, i found one problem in your code: if you try to run it twice, the second time you can only set the x-varaible. The reason is clear; you dont reset cCurrentVar and iInputLoop. And i would use a switch instead of if/if else/else if. This is the new code:
You're of course right about both things. Some stupid mistakes.
However, i dont understand one thing:
I have tested the code before posting it, and it worked fine. I agree iQuad[4] is invalid, so why didnt I got an error?
Undefined behaviour. It will tend to work in smaller applications because that memory is likely not allocated elsewhere. However, in larger applications that memory is surely going to be used. So by changing the value of it you end up changing an unknown value and having undefined behaviour.
#include <iostream>
//gets input of the user, without crash ;)
int getint(int min,int max)
{
int input;
char temp[100];
while (input<min||input>max||(input==0 && temp[0]!='0'))
{
std::cin.getline(temp, 100);
input=strtol(temp,0,10);
if (input<min||input>max||(input==0 && temp[0]!='0'))
std::cout<<"Not an option!\n";
}
}
usingnamespace std;
int main()
{
int oldvalue[2]={1,1};
int newvalue;
int input;
std::cout<<"How many numbers?\n";
input=getint(1,46);
cout<<oldvalue[0]<<",\n"<<oldvalue[1]<<",\n";
for (int i=3;i<=input;i++)
{
newvalue=oldvalue[0]+oldvalue[1];
oldvalue[0]=oldvalue[1];
oldvalue[1]=newvalue;
cout<<newvalue;
if (i<input)
{
cout<<",\n";
}
//here you can add the next\quit stuff
}
cin.ignore();
return 0;
}
There is a problem in the code above i dont get: it works fine for the first 46 numbers, and after that it start to put out negative numbers...?
So i set the userinput to maximaal 46 :) It is a lot faster than your code.
You can also do it without any loops. Don't know if it is faster.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int n,m;
cin >> n;
m = pow((1+sqrt(5))/2,n)/sqrt(5) + .5;
cout << "The "<<n<<"th Fibonacci number is "<< m <<".\n";
}
I dont totally understand how your code works, but its problebly faster, since it only calculates once :)
But your code has the same problem as mine: after the 46st number, it start to put out negative numbers (different negative numbers then mine program, wich makes it even stranger).
Can anyone tell me wy both programs put out negative values after 46?