Hi,

I need some help with average calculation. I have a homework where i must find average value, but this one is quite tricky, atleast for me. usualy it goes like that 1+2 average is 1,5.
I have to do it like this:

If i input 15 then program should understand that as 1+5 and average of that is 3.


I have failed to find/figure this one out.


Thank you in advance.

Dani AI

Generated

Short, practical summary tied to the thread: the task is to compute the average of the decimal digits of an input (so 15 -> 1+5 = 6, average = 3). Two common approaches were already suggested: numeric digit extraction with modulo/divide (hints from and ) and a simple string-based parse (an alternative that avoids loss of leading zeros and makes validation easier). gave a useful outline but, as noted, be sure to take the remainder (n % 10) before you divide (n /= 10).

A robust, compact C++ approach that handles negatives and invalid characters is to read the input as a string, skip an initial sign, validate each character, sum digits and count them, then compute a floating-point average. Example:

#include <iostream>
#include <string>
#include <cctype>

int main() {
    std::string s;
    std::cout << "Enter an integer: ";
    if (!(std::cin >> s)) return 0;

    size_t i = 0;
    if (!s.empty() && (s[0] == '+' || s[0] == '-')) i = 1;

    long long sum = 0;
    int count = 0;
    for (; i < s.size(); ++i) {
        if (!std::isdigit(static_cast<unsigned char>(s[i]))) {
            std::cerr << "Invalid input: non-digit present\n";
            return 1;
        }
        sum += s[i] - '0';
        ++count;
    }

    double average = count ? static_cast<double>(sum) / count : 0.0;
    std::cout << "Average of digits: " << average << '\n';
}

Troubleshooting and teacher/edge-case notes: if you use numeric extraction, always do digit = n % 10 before n /= 10. Cast to double (or divide by 2.0, count as double) to avoid integer division. To preserve leading zeros (e.g., "05") read as string; reading into an integer will drop them. For very long inputs use 64-bit accumulation to avoid overflow. If a specific formatting (fixed decimals, rounding) is required, format the output with iomanip.

Recommended Answers

All 7 Replies

A couple of comments for you to consider:

  • You will need a variable of type float or double to store and print the average
  • You can use modulo arithmetic to get the digits of a number (%)

These two hints should point you in the right direction. Let me know if I am being too vague but I am trying to give you a hint without telling you exactly what to do... ;)

Welcome aboard. A few things additionally. This is an outline:

<Your headers>

using namespace std;

int main ()
{
1. declare a few variables...int, float...
2. cout<<"enter two numbers to get the average"<<endl;//ask the user ro input two digits.
3. cin>>num1>>num2;//makes the user enter two numbers
4. You get the total of the numbers and then divide by the amt of numbers/digits.
5. You can figure out the rest. Hope this helps.

A couple of comments for you to consider:

  • You will need a variable of type float or double to store and print the average
  • You can use modulo arithmetic to get the digits of a number (%)

These two hints should point you in the right direction. Let me know if I am being too vague but I am trying to give you a hint without telling you exactly what to do... ;)

I understand and respect that, but since im kinda new to this thing, could you please point the direction where should I look for some info on modulo arithmetic? google seems to find alot except basics on this.

Welcome aboard. A few things additionally. This is an outline:

<Your headers>

using namespace std;

int main ()
{
1. declare a few variables...int, float...
2. cout<<"enter two numbers to get the average"<<endl;//ask the user ro input two digits.
3. cin>>num1>>num2;//makes the user enter two numbers
4. You get the total of the numbers and then divide by the amt of numbers/digits.
5. You can figure out the rest. Hope this helps.

Thanks, but the hardest thing in this assingment is that I dont need to input 2 digits, I know how to do that :)

It goes like this, I input one digit, lets say 15 for example, the program should understand this one digit as 1+5 and calculate its average. 1+5=6/2 = 3 like this :)

>>modulo arithmetic
Not much to it -- modulo is the result after division. For example 15/10 = remainder 5. So 15 % 10 = 5. 27 % 10 = 7. After that just do normal division by 10 to remove the last digit from the number.

Ok...now i get you. I perhapds did mis-understand you initially. So what you'll have to do (this isn't the entire answer, but it's a start):

#include <iostream.h>
//other headers
using namespace std;
main()
{

int num; //user input
int a,b;  //used for integer division and modulus operations
cout <<"Enter a two digit number." <<endl;
cin >> num;
#= #/10; //do calculation                           
# = #%10;//do calculation
cout<<#<<#<<endl;
double average = (# + # )/2;
cout<<average<<endl;

enough spoon feeding, you can figure out how to do the rest...or fill in the blanks, show us what you've come up with!

zandiago: lines 11 and 12 are reversed -- you have to do the mod before the division.

Ok...thx for spotting that. Age....what else to blame. Pretty straight-forward assignment. To original poster. If your professor requires you to do it for a larger number...let's say....a 6 digit number, then you'll have to use the operations 6 times.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.