Jump to content

Whats wrong with my code? I wanna get the summation of the array , C++

KieranTHeBesT
Go to solution Solved by Eigenvektor,

Please, post code as text in a code block… makes it much easier for people to try your code. If you're asking what the problem is, it's also usually a good idea to tell people if it just doesn't behave as expected (and what's happening instead) or if you're getting a compiler error (which one?)

 

At a quick glance, your array contains doubles, but your sum total is an int. Either change your sum to a double, or round your values to int before trying to add them.

 

~edit: Here's a working example

Spoiler
#include <iostream>

int main() {
	double prices[] = {
		6.99,
		8.5,
		42.9,
		105.4,
		42,
		98.1,
	};

	int size = sizeof(prices) / sizeof(double);

	double total = 0;

	for (int i = 0; i < size; i++) {
		total += prices[i];
	}

	std::cout << "sum of " << size << " numbers is: " << total << std::endl;
}

 

Please, post code as text in a code block… makes it much easier for people to try your code. If you're asking what the problem is, it's also usually a good idea to tell people if it just doesn't behave as expected (and what's happening instead) or if you're getting a compiler error (which one?)

 

At a quick glance, your array contains doubles, but your sum total is an int. Either change your sum to a double, or round your values to int before trying to add them.

 

~edit: Here's a working example

Spoiler
#include <iostream>

int main() {
	double prices[] = {
		6.99,
		8.5,
		42.9,
		105.4,
		42,
		98.1,
	};

	int size = sizeof(prices) / sizeof(double);

	double total = 0;

	for (int i = 0; i < size; i++) {
		total += prices[i];
	}

	std::cout << "sum of " << size << " numbers is: " << total << std::endl;
}

 

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

Also unless my eyes are messing with me, there's 18 numbers inside, and arrays start by default at 0 , so you have prices[0] .. prices[17]

 

If you don't know the actual number of items ahead of time, you could also use foreach : https://www.digitalocean.com/community/tutorials/foreach-loop-c-plus-plus

You could increment some variable in the foreach loop to determine the number of items if it's unknown and don't want to use sizeof as in the example above.

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×