C++ Decimal Math & Variable Declaration

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 7360 Views - Last Post: 11 January 2011 - 12:29 PM Rate Topic: -----

#1 WCoaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 03-January 11

C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 10:07 AM

Hi All

A couple of quick questions.

  • Why does this code not return a decimal answer
    int const limit = 5;
    int sum;
    double average;
    int marks[]={7,5,8,1,3};
    
    double Avg(int marks[])
    {
        for (int i = 0; i < limit; i++)
        {
            sum += marks[i];
        }
        average = sum / limit;
        return average;
    }
    

  • Why does changing sum to a double matter?
    int const limit = 5;
    double average, sum;
    int marks[]={7,5,8,1,3};
    
    double Avg(int marks[])
    {
        for (int i = 0; i < limit; i++)
        {
            sum += marks[i];
        }
        average = sum / limit;
        return average;
    

  • Here is my final solution making the question irrelevant, but I would still like to understand the logic.
    int const limit = 5;
    double average;
    int marks[limit];
    
    double Avg(int marks[])
    {
        for (int i = 0; i < limit; i++)
        {
            average += marks[i];
        }
        average /= limit;
        return average;
    }
    


Any suggested reading on C++ math would be greatly appreciated. I just noticed that
cout << 15/4;
returns 3 and not 3.75. That was unexpected too!!! :omg:

Also I am looking for documentation on code format etiquette and accepted C++ syntax. It is very hard to tell what is current when trying to learn from the web.

Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: C++ Decimal Math & Variable Declaration

#2 lepinat0r  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 33
  • Joined: 21-December 10

Re: C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 10:14 AM

Your answer variable has to be a double. I believe you also have to have at least one double in the calculation part.

So you have x, y, z:
double z = int x / double y


When you are trying to do:
int z = int x / double y


or

double z = int x / int y


z's decimal places get truncated or cut off.

This post has been edited by lepinat0r: 09 January 2011 - 10:16 AM

Was This Post Helpful? 0
  • +
  • -

#3 Ancient Dragon  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 81
  • View blog
  • Posts: 679
  • Joined: 19-July 09

Re: C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 10:23 AM

None of the snippets you posted are 100% correct -- all of them fail to initialize sum variable so it contains just some random number.

There is no reason for all those global variables, for example sum might as well be a local variable in the Avg function.

As for your specific question -- the first code snippet does not return a double value because sum was declared as an integer, and integers can not contain decimal values. So when you add a double to an int the decimals are just truncated. Example: sum + 2.123 is the same as sum + 2. And that is also the answer to your second question. Converting sum to a double preserves all the decimals too.

As for the last question, 15/4 is using integer division, again discarding the remainder of the division. If you want the decimals then do this: 15.0/4 or 15/4.0. Adding the .0 to either of the numbers tells the compiler to generate code to do double division.

This post has been edited by Ancient Dragon: 09 January 2011 - 10:25 AM

Was This Post Helpful? 2
  • +
  • -

#4 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1622
  • View blog
  • Posts: 5,709
  • Joined: 03-August 09

Re: C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 10:33 AM

1) the only way i can see that producing a decimal answer is due to the in accuracy of floating point numbers.
2) becuase the answer should result in a double, double+int should yield type double.
Was This Post Helpful? -1
  • +
  • -

#5 WCoaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 03-January 11

Re: C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 11:25 AM

Thanks for the answers.

This is indeed what I intuitively deduced.

Does anyone know of a "technical reference" to floating point math? I assume this is a generic issue related to CPU's and not any specific language. Is that correct?

This post has been edited by WCoaster: 09 January 2011 - 11:25 AM

Was This Post Helpful? 0
  • +
  • -

#6 jimblumberg  Icon User is online

  • member icon


Reputation: 3987
  • View blog
  • Posts: 12,298
  • Joined: 25-December 09

Re: C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 11:31 AM

Quote

I assume this is a generic issue related to CPU's and not any specific language. Is that correct?


No that is not correct. It is not related to CPU's. It is related to how floating point numbers are stored in memory.

Please see this link: Floating Point.

Jim
Was This Post Helpful? 1
  • +
  • -

#7 ishkabible  Icon User is offline

  • spelling expret
  • member icon




Reputation: 1622
  • View blog
  • Posts: 5,709
  • Joined: 03-August 09

Re: C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 11:36 AM

to elaborate ANSI regulates this stuff, the only thing you CPU has to do with it is at the assembly level your instructions change depending on witch architecture your using. if your using MIPS or ARM then your binary's are going to be different from x86 or x64 but the effects should be the same given that the compiler complies the code according to ANSI standards.
Was This Post Helpful? 1
  • +
  • -

#8 WCoaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 03-January 11

Re: C++ Decimal Math & Variable Declaration

Posted 09 January 2011 - 05:52 PM

View Postjimblumberg, on 09 January 2011 - 10:31 AM, said:

Please see this link: Floating Point.

Jim


Thanks for this Jim!!!
A great resource.
Was This Post Helpful? 0
  • +
  • -

#9 WCoaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 03-January 11

Re: C++ Decimal Math & Variable Declaration

Posted 10 January 2011 - 03:15 PM

View PostAncient Dragon, on 09 January 2011 - 09:23 AM, said:

None of the snippets you posted are 100% correct -- all of them fail to initialize sum variable so it contains just some random number.

There is no reason for all those global variables, for example sum might as well be a local variable in the Avg function.

As for your specific question -- the first code snippet does not return a double value because sum was declared as an integer, and integers can not contain decimal values. So when you add a double to an int the decimals are just truncated. Example: sum + 2.123 is the same as sum + 2. And that is also the answer to your second question. Converting sum to a double preserves all the decimals too.

As for the last question, 15/4 is using integer division, again discarding the remainder of the division. If you want the decimals then do this: 15.0/4 or 15/4.0. Adding the .0 to either of the numbers tells the compiler to generate code to do double division.


Thank You Ancient Dragon!!!

Yesterday I was a little miffed at your comments being a bit off topic, (unnecessary Global variables and uninitialized variables). I was quite proud of how graceful my little code looked and worked.

However, the comments stuck with me while I researched more into my original question of floating point math. Somewhere along the line I came across an article about "Making it work and making it work right". I also learned about printf and the cstdio library.

These two items together made it painfully clear why too global a declaration can be a bad thing and obviously that variables must be initialized.

So, I thank you again for helping me to DIC better. I also request another measure of inspection.

Can anyone who is feeling generous please point out obvious deficiency in process or logic or anything else I may be blissfully unaware of in the following.

#include <iostream>
#include <cstdio>

using namespace std;

//limit entries to five and make it easy to change
int const limit = 5;
int marks[limit];

// Averag the entries
double Avg(int marks[])
{
    double average = 0;
    for (int i = 0; i < limit; i++)
    {
        average += marks[i];
    }
    average /= limit;
    return average;
}

// Find the highest entry
int HighMark(int marks[])
{
    int high = 0;
    for (int i=0; i < limit; i++)
    {
        if (marks[i] > high)
        {
            high = marks[i];
        }
    }
    return high;
}

//Total the entries less than average
int LowMarks(int marks[], double average)
{
    int markslowavg = 0;
    for (int i = 0; i < limit; i++)
    {
       if (marks[i] < average)
       {
           markslowavg ++;
       }
    }
    return markslowavg;
}

int main()
{
    int high = 0, markslowavg = 0;
    double average = 0;
    for ( int i = 0; i < limit; i++)
    {
        cout << "Please enter a mark: ";
        cin >> marks[i];
    }
    average = Avg(marks);
    high = HighMark(marks);
    markslowavg = LowMarks(marks, average);
    printf("Average Mark Is: %.3f\nHighest Mark Is: %d\nNumber of Marks Less than Average is: %d\n",average, high, markslowavg);
return 0;
}



Thank You
Was This Post Helpful? 0
  • +
  • -

#10 jimblumberg  Icon User is online

  • member icon


Reputation: 3987
  • View blog
  • Posts: 12,298
  • Joined: 25-December 09

Re: C++ Decimal Math & Variable Declaration

Posted 10 January 2011 - 03:36 PM

When I compile this code these are the warning messages I get.

Quote

||=== c++homework, Debug ===|
main.cpp|11|warning: declaration of ‘marks’ shadows a global declaration|
main.cpp|8|warning: shadowed declaration is here|
main.cpp||In function ‘int HighMark(int*)’:|
main.cpp|23|warning: declaration of ‘marks’ shadows a global declaration|
main.cpp|8|warning: shadowed declaration is here|
main.cpp|37|warning: declaration of ‘marks’ shadows a global declaration|
main.cpp|8|warning: shadowed declaration is here|


You will notice that they all pertain to your global variable "marks[]". Since you are passing marks[] into your functions you have no need of a global variable, put it into main.

In main you are using both C++ input/output (cin) and C input/output (printf). You should not mix both iostream and cstudio functions. If you are programming in C++ then use iostreams not studio streams. There are methods to format the output available for the iostreams so you should not need printf.

Jim
Was This Post Helpful? 0
  • +
  • -

#11 WCoaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 03-January 11

Re: C++ Decimal Math & Variable Declaration

Posted 10 January 2011 - 04:05 PM

View Postjimblumberg, on 10 January 2011 - 02:36 PM, said:

When I compile this code these are the warning messages I get...

...You will notice that they all pertain to your global variable "marks[]". Since you are passing marks[] into your functions you have no need of a global variable, put it into main.


DONE. Why do the functions recognize an array from main but not a variable? (ie. average)

View Postjimblumberg, on 10 January 2011 - 02:36 PM, said:

In main you are using both C++ input/output (cin) and C input/output (printf). You should not mix both iostream and cstudio functions. If you are programming in C++ then use iostreams not studio streams. There are methods to format the output available for the iostreams so you should not need printf.


Is there a tutorial that shows how to recreate my line 62 using iostream only? Other than...
cout << "Average Mark Is: " << average << endl;
cout << etc...

Was This Post Helpful? 0
  • +
  • -

#12 jimblumberg  Icon User is online

  • member icon


Reputation: 3987
  • View blog
  • Posts: 12,298
  • Joined: 25-December 09

Re: C++ Decimal Math & Variable Declaration

Posted 10 January 2011 - 04:59 PM

Try this link: Formatting with iostreams.


Jim
Was This Post Helpful? 0
  • +
  • -

#13 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5760
  • View blog
  • Posts: 12,573
  • Joined: 16-October 07

Re: C++ Decimal Math & Variable Declaration

Posted 11 January 2011 - 05:37 AM

You're still using globals. Shouldn't limit mean maximum number of values allowed? You're not really using it that way, so it's unclear.

It's not hard to get rid of the globals...
#include <iostream>

using namespace std;

int Sum(int marks[], int size) {
	int sum = 0;
	for (int i = 0; i < size; i++) {
		sum += marks[i];
	}
	return sum;
}

double Avg(int marks[], int size) { return (double)Sum(marks, size) / size; }

int HighMark(int marks[], int size) {
	int high = 0;
	for (int i=0; i < size; i++) {
		if (marks[i] > high) {
			high = marks[i];
		}
	}
	return high;
}

int LowMarks(int marks[], int size, double average) {
	int markslowavg = 0;
	for (int i = 0; i < size; i++) {
		if (marks[i] < average) {
			markslowavg ++;
		}
	}
	return markslowavg;
}

void showResults(int marks[], int size) {
	double average = Avg(marks, size);
	cout << "Average Mark Is: " << average << endl;
	cout << "Highest Mark Is: " << HighMark(marks, size) << endl;
	cout << "LowMarks: " << LowMarks(marks, size, average) << endl;
}

int main() {
	const int limit = 5;
	int marks[limit];

	for ( int i = 0; i < limit; i++) {
		cout << "Please enter a mark: ";
		cin >> marks[i];
	}
	showResults(marks, limit);
	return 0;
}



Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#14 WCoaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 03-January 11

Re: C++ Decimal Math & Variable Declaration

Posted 11 January 2011 - 11:29 AM

View Postbaavgai, on 11 January 2011 - 04:37 AM, said:

You're still using globals. Shouldn't limit mean maximum number of values allowed? You're not really using it that way, so it's unclear.

It's not hard to get rid of the globals...

Hope this helps.


In my mind limit meant limit the number of allowed entries, so... yes and no. lol

Thank you for this rework. I learned a few things in there.

Is the Sum function not a little excessive as I do not require a sum total other than for the average routine?

I can see that it is indeed a unique process and therefore a candidate for a function. I suppose it may be advantageous for anticipated future needs to split out functions whenever possible. Is this the reason? Are there other reasons?

Thanks again.

This post has been edited by WCoaster: 11 January 2011 - 11:30 AM

Was This Post Helpful? 0
  • +
  • -

#15 WCoaster  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 32
  • Joined: 03-January 11

Re: C++ Decimal Math & Variable Declaration

Posted 11 January 2011 - 12:04 PM

Just for kicks. Here is the answer from the assignment.pdf I found online. It is from the Fall 2001 semester at U of Alberta CMPUT 101 C++ Programming.

7. Write a program that prompts the user to enter 5 exam marks (design your program such that it would be easy to change if we wanted it to work for more than 5 exams). The program then displays the average mark, the highest mark, and number of marks entered less than the average mark. For example, when executing the program and inputting 20, 30, 10, 40, and 50 the running session will look as follows:
Enter a mark: 20
Enter a mark: 30
Enter a mark: 10
Enter a mark: 40
Enter a mark: 50
Average mark is: 30.0
Highest mark is: 50
Number of marks less than the average: 2


//
// Given 5 exam marks, this program calculates the average mark, the highest mark, and
// how many of the marks are greater than the average //
#include <iostream.h>
void main()
{
const int MAXNUMBERS = 5;
int i, n, max, lessthan, N[MAXNUMBERS];
double sum, average;
max = 0;
sum = 0;
i = 0;
while ( i < MAXNUMBERS ) {
cout << "Enter a mark: ";
cin >> n;
N[i] = n;
sum = sum + N[i];
if ( N[i] > max ) {
max = N[i];
}
i = i + 1;
}
average = sum / MAXNUMBERS;
lessthan = 0;
i = 0;
while ( i < MAXNUMBERS ) {
if ( N[i] < average ) {
++lessthan;
}
i = i + 1;
}
cout << endl;
cout << "Average mark is: " << average << endl;
cout << "Highest mark is: " << max << endl;
cout << "Number of marks less than the average: " << lessthan << endl;
}


Just a little different from what we came up with. :smartass:
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2