Calculating 2 numbers in 3 ways: code doesn´t work
Hi,
I´m trying to learn C++, and I´m currently making a small program, but my code doesn´t work. Maybe someone here knows what I´m doing wrong!
I want the user to digit two numbers, and choose a=addition, m=multiplication and k=square-sum. And this does work with the two number, but I want to include al the numbers between the two numbers: for example, 3 and 5, with "a" = 3+4+5=12.
Hope someone could help!!
Here´s my idiotic code:
// Func. to calculate according to choises in LasEttTal and in lasOp
int berakna (int tal1, int tal2, char op)
{
int summa=0; //make it zero
cout<<tal1<<endl;
cout<<tal2<<endl;
cout<<op<<endl;
if(op=='a')
{
for(int i=tal1; i<=tal2; i++) //tal1 and tal 2 is the two choosen numbers
{
summa=tal1+tal2; //addition
cout<<i<<summa<<endl;
}
}
if(op=='m')
{
for(int i=tal1; i<=tal2; i++)
{
summa=tal1*tal2; //multiplication
cout<<i<<summa<<endl;
}
}
if(op=='k')
{
for(int i=tal1; i<=tal2; i++)
{
summa=(tal1*tal1) + (tal2*tal2); // Square-sum
cout<<i<<summa<<endl;
}
}
return summa;
}
Re: Calculating 2 numbers in 3 ways: code doesn´t work
What do you think this line is doing?
summa=tal1+tal2;
Does that seem like what you really want to do?
Re: Calculating 2 numbers in 3 ways: code doesn´t work
When posting code, please use code tags. Go Advanced, select the formatted code and click '#'.
For the for loops, i starts at the value of tal1 and gets incremented by 1 each time around the loop until it's value is greater than tal2. Then the loop exits. If you want to sum, multiply etc the numbers with the range tal1, tal2 then as GCDEF suggested in post #2, is summa = tal1 + tal2 going to achieve what is required?
Re: Calculating 2 numbers in 3 ways: code doesn´t work
Thanks! Yeas, it´s not logical I realize to do the "Summa=tal1+tal2" etc. Instead I tried:
if(op=='a')
{
for(tal1; tal1<=tal2; tal1++)
{
summa+=tal1; //addition
cout<<tal1<<summa<<endl;
}
}
if(op=='m')
{
for(tal1; tal1<=tal2; tal1++)
{
summa*=tal1;//multiplication
cout<<tal1<<summa<<endl;
}
}
Which worked with addition, but not multiplication.
Sorry I´m totally new in programming...
Re: Calculating 2 numbers in 3 ways: code doesn´t work
Code:
for(int i = tal1; i <= tal2; ++i)
{
summa += i;
cout << i << " " << summa << endl;
}
See http://www.learncpp.com/cpp-tutorial/57-for-statements/ for more info about for loops and c++