Buscar

Write a function that receives two parameters a and b and swaps the value of a with the value of b if the value of a is greater than that of b; the...

Write a function that receives two parameters a and b and swaps the value of a with the value of b if the value of a is greater than that of b; the goal is to have, in the end, the smaller of the two values in a and the larger in b. For example, if a = 5 and b = 3, then the values of the two variables should be swapped, but if a = 2 and b = 7, then the order is already correct and it is not necessary to swap the values. Use pass-by-reference parameter passing to be able to affect the value of the variables. Write a program to test the function.


Essa pergunta também está no material:

Introducao_a_Progrmacao
103 pág.

Introdução à Programação Universidade Estácio de SáUniversidade Estácio de Sá

💡 1 Resposta

User badge image

Ed Verified user icon

Claro! Aqui está uma possível implementação da função em Python: ```python def swap_values(a, b): if a > b: a, b = b, a # Testando a função a = 5 b = 3 print("Antes da troca: a =", a, "e b =", b) swap_values(a, b) print("Depois da troca: a =", a, "e b =", b) a = 2 b = 7 print("Antes da troca: a =", a, "e b =", b) swap_values(a, b) print("Depois da troca: a =", a, "e b =", b) ``` Neste exemplo, a função `swap_values` recebe dois parâmetros `a` e `b`. Se o valor de `a` for maior que o valor de `b`, os valores são trocados utilizando a técnica de atribuição múltipla em Python. Dessa forma, o menor valor fica em `a` e o maior valor em `b`. Caso contrário, os valores não são trocados. No programa de teste, definimos valores iniciais para `a` e `b`, imprimimos os valores antes da troca, chamamos a função `swap_values` e, por fim, imprimimos os valores após a troca.

0
Dislike0

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

✏️ Responder

SetasNegritoItálicoSublinhadoTachadoCitaçãoCódigoLista numeradaLista com marcadoresSubscritoSobrescritoDiminuir recuoAumentar recuoCor da fonteCor de fundoAlinhamentoLimparInserir linkImagemFórmula

Para escrever sua resposta aqui, entre ou crie uma conta

User badge image

Outros materiais