jett Posted June 2, 2013 at 04:29 PM Report #510561 Posted June 2, 2013 at 04:29 PM (edited) Olá, estou fazendo um programa que soma recursivamente todos os elementos da direita para esquerda, porém estão acontecendo alguns erros. Vocês poderiam me ajudar? #include <stdlib.h> #include <stdio.h> int criar(A, n){ int cont = 0; while(cont < n){ A[cont]= cont+1; } return A; } int Soma(k, n, A){ int s; if(k > n){ s = 0; } else{ s = A[k] + Soma(k+1, n, A); } return s; } int main(){ int n; printf("Digite o número de elementos: "); scanf("%d", &n); int A[n]; A = criar(A, n); int s = Soma(1, n, A); printf("Soma: %d", s); return 0; } Os erros que aparecem: ||In function 'criar':| |7|error: subscripted value is neither array nor pointer nor vector| ||In function 'Soma':| |18|error: subscripted value is neither array nor pointer nor vector| ||In function 'main':| |32|error: incompatible types when assigning to type 'int[(sizetype)(n)]' from type 'int'| ||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===| Edited June 2, 2013 at 06:59 PM by pmg GeSHi
HappyHippyHippo Posted June 2, 2013 at 04:34 PM Report #510562 Posted June 2, 2013 at 04:34 PM nenhuma das tuas definições de função está correctamente efectuada http://opencbp.sourceforge.net/en_US.ISO8859-1/books/opencbook/func.prototypes.html não existe a declaração de tipo no protótipo das funções IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
jett Posted June 2, 2013 at 05:42 PM Author Report #510569 Posted June 2, 2013 at 05:42 PM (edited) Ah, havia esquecido de colocar os tipos dos parâmetros, mas agora o resultado está saindo errado, o que eu devo fazer? O código ficou assim: #include <stdlib.h> #include <stdio.h> int Soma(int k, int n, int A[]); int main(){ int n; printf("Digite o número de elementos: "); scanf("%d", &n); int A[n]; int cont = 0; int i = n; while(cont < n){ A[cont]= cont+1; cont ++; } //A = criar(A, n); int s = 0; s = Soma(1, n, A); printf("Soma: %d\n", s); return 0; } int Soma(int k, int n, int A[n]){ int s; if(k > n){ s = 0; } else{ s = A[k] + Soma(k+1, n, A); } return s; } Edited June 2, 2013 at 06:07 PM by pmg GeSHi
HappyHippyHippo Posted June 2, 2013 at 06:06 PM Report #510573 Posted June 2, 2013 at 06:06 PM (edited) o teu problema está aqui : int Soma(int k, int n, int A[n]){ // .. if(k > n) { se tens 5 elementos no array, o último índice válido é 4, no entanto, quanto k = 5, não estás a parar a recursividade ---------- como o teu código está válido (tirando o bug apresentado) vê agora como a quantidade de código desnecessário que tens é descomunal ... #include <stdio.h>unsigned int Soma(unsigned int n) { if (n == 0) return 0; return n + Soma(n-1);}int main(){ unsigned int n; printf("Digite o número de elementos: \n"); scanf("%u", &n); printf("Soma: %u\n", Soma(n)); return 0;}[/Code] Edited June 2, 2013 at 06:07 PM by HappyHippyHippo IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
pmg Posted June 2, 2013 at 06:10 PM Report #510574 Posted June 2, 2013 at 06:10 PM O elemento A[n] não existe. No entanto estas a tentar soma-lo na funcao Soma(). Alem disso, o primeiro elemento é o A[0] e nao estas a considerar este elemento na funcao. What have you tried? Não respondo a dúvidas por PM A minha bola de cristal está para compor; deve ficar pronta para a semana. Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!
jett Posted June 2, 2013 at 06:33 PM Author Report #510575 Posted June 2, 2013 at 06:33 PM (edited) Obrigada pessoal, funcionou aqui. O código ficou: #include <stdlib.h> #include <stdio.h> int Soma(int k, int n, int A[]); int main() { int n; printf("Digite o número de elementos: "); scanf("%d", &n); int A[n-1]; int cont = 0; while(cont < n) { A[cont]= cont+1; cont ++; } int s; s = Soma(1, n, A); printf("Soma: %d\n", s); return 0; } int Soma(int k, int n, int A[n]) { int s; if(k > n) { s = 0; } else { s = A[k-1] + Soma(k+1, n, A); } return s; } Edited June 2, 2013 at 07:00 PM by pmg GeSHi
pmg Posted June 2, 2013 at 07:06 PM Report #510578 Posted June 2, 2013 at 07:06 PM O teu codigo tem erro(s) printf("Digite o número de elementos: "); scanf("%d", &n); int A[n-1]; int cont = 0; while(cont < n) { A[cont]= cont+1; cont ++; } Neste bocadinho de codigo, estas a aceder a um elemento do array que nao existe. Imagina que se introduz 5 para a variavel n. Nesse caso cria-se um array com espaco para 4 elementos: os elementos com indices 0, 1, 2, e 3. Depois, no ciclo while, vais tentar meter o valor 4 em A[4]. Mas A[4] nao existe!!!! Se conseguires pensar no elemento de indice 0 como o primeiro elemento do array, e evitar aqueles k-1 o teu programa fica mais facil de entender. So precisas de te habituar a ideia de "indice 0" (que e fundamental para perceber C). What have you tried? Não respondo a dúvidas por PM A minha bola de cristal está para compor; deve ficar pronta para a semana. Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now