Hello everyone, so I have a hard one. So far I have the code to run for normal numbers. Here it's asking me to write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. The code also needs negative numbers too. As you can see here, if you were to input 5624; it will come out as "5 6 2 4 Sum:17". My goal is to have -2345 as 2 3 4 5. Could anyone be so kind to explain how this works? Much appreciated coders.
#include <iostream>
usingnamespace std;
int main()
{
int a = 0;
int b [100] = {0};
int n = 0;
int sum = 0;
cout << "Show me how many numbers you can give." << endl;
cin >> a;
cout << endl;
while (a > 0)
{
b[n] = a%10;
a /= 10;
n++;
}
for (int i=n; i>0; i--)
{
printf("%d ", b[i-1]);
sum+=b[i-1];
}
printf(" Sum: %d ",sum);
cin.get(); cin.get();
return 0;
}
//...
cout << endl;
if (/* a is negative */)
{
a = /* a but made positive using arithmetic*/;
}
while (a > 0)
//...
Alternatively, instead of the if statement and the code inside it, there is a single function that calculates the absolute value of an integer in C++, which you could use instead. I encourage you to try searching for it. As a hint, it's in the <cstdlib> header.
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main()
{
bool negative{};
int a = 0;
int b [100] = {0};
int n = 0;
int sum = 0;
cout << "Show me how many numbers you can give: ";
cin >> a;
if (a < 0)
{
negative = true;
a = abs(a);
}
cout << endl;
while (a > 0)
{
b[n] = a%10;
a /= 10;
n++;
}
if (negative)
{
std::cout << "- ";
}
for (int i =n ; i > 0; i--)
{
printf("%d ", b[i-1]);
sum+=b[i-1];
}
if (negative)
{
sum *= -1;
}
std::cout << " Sum: " << sum << '\n';
cin.get(); cin.get();
return 0;
}
I made the changes in the shell program here.
It gives the output of:
Show me how many numbers you can give: -2345
- 2 3 4 5 Sum: -14
See what you think.
@Albatross,
I think the function that you mean is in the <cmath> header file not the <cstdlib> file.
#include <iostream>
usingnamespace std;
int main()
{
int a = 0;
int b [100] = {0};
int n = 0;
int sum = 0;
cout << "Show me how many numbers you can give." << endl;
cin >> a;
if(a < 0)
a = -a;
cout << endl;
while (a != 0)
{
b[n] = a%10;
a /= 10;
n++;
}
for (int i=n; i>0; i--)
{
printf("%d ", b[i-1]);
sum+=b[i-1];
}
printf(" Sum: %d ",sum);
cin.get(); cin.get();
return 0;
}
Defined in header <cstdlib>
Defined in header <cmath> (since C++17)
EDIT 2: Sorry if I was overly curt with this message. I was in a little bit of a rush when typing it originally. And, full disclosure, I almost typed <cmath> as well, and only remembered at the last moment.