Jump to content

Soma de n float elementos


Upper
 Share

Recommended Posts

Oi boas

Tou com uma duvida

preciso de criar um programa que receba um vector de x elementos do tipo float e faça a soma desses mesmos elementos de momento tenho este codigo:

#include <stdio.h>


int main(){

int n;
int ind;

printf("Quantos elementos e que sao: ");
scanf(" %d", &n);

int v[10];
for(ind = 0; ind < n; ind ++){
	v[ind]=0;
	printf("Elemento %d = ",(ind+1));
	scanf(" %d", &v[ind]); 

}

float total=0;
for(ind = 0 ; ind < n; ind++);
{
	total += v[ind];
}


printf(" %f", total);


}

So que ele nao efectua bem a soma do total. ALguem me pode ajudar?

Link to comment
Share on other sites

#include <stdio.h>


int main(){

int n;
int ind;

printf("Quantos elementos e que sao: ");
scanf(" %d", &n);

float v[10];
for(ind = 0; ind < n; ind ++){

	printf("Elemento %d = ",(ind+1));
	scanf(" %f", &v[ind]); 

}

float total=0;
for(ind = 0 ; ind < n; ind++);
{
	total = (float) (total + v[ind]);

}


printf(" %f", total);


}

Continua com o mesmo erro, mesmo depois das duas modificacoes

Link to comment
Share on other sites

Ja agora outra duvida sobre o mesmo programa:

Agora quero passar a parte que efectua a soma para uma funcao

#include <stdio.h>

float soma(int n);
int main(){

int n, ind;

printf("Quantos elementos e que sao: ");
scanf(" %d", &n);

float v[10];
for(ind = 0; ind < n; ind ++){

	printf("Elemento %d = ",(ind+1));
	scanf(" %f", &v[ind]); 

}
soma(n);
}

float soma(int n){

int ind;
float v[10];
float total=0;
for(ind = 0 ; ind < n; ind++)
{
	total = (float) (total + v[ind]);

}


printf(" %f", total);


}

so que agora quando executo o programa este da lixo no resultado do total. O que me falta?

Sera que o n que esta em soma(n) e o erro?

Link to comment
Share on other sites

#include <stdio.h>

float soma(int n, float v[]);

int main(){

int n, ind;

printf("Quantos elementos e que sao: ");
scanf(" %d", &n);

float v[10];
for(ind = 0; ind < n; ind ++){

	printf("Elemento %d = ",(ind+1));
	scanf(" %f", &v[ind]); 

}
soma(n,v[10]);
}

float soma(int n, float v[]){

int ind;
float v[10];
float total=0;
for(ind = 0 ; ind < n; ind++)
{
	total = (float) (total + v[ind]);

}


printf(" %f", total);


}

E assim que o vector esta bem declarado?

Link to comment
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
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.