A seção a seguir apresenta soluções em C para uma variedade de desafios de programação, cada um abordando um problema específico com uma abordagem distinta.
Verificar Caractere Imprimível
#include <stdio.h>
int main() {
int charCode;
scanf("%d", &charCode);
if (charCode >= 32 && charCode <= 126) {
printf("%c\n", charCode);
} else {
printf("Caractere Invisível!\n");
}
return 0;
}
Este snippet verifica se um código ASCII representa um caractere imprimível (entre espaço e til). Se estiver dentro do intervalo, imprime o caractere; caso contrário, informa que é um caractere invisível.
Cálculo de Média Ponderada
#include <stdio.h>
int main() {
int numItems;
scanf("%d", &numItems);
double totalSum = 0.0;
double weightedSum = 0.0;
double totalWeight = 0.0;
for (int i = 0; i < numItems; ++i) {
double value, weight;
scanf("%lf %lf", &value, &weight);
totalSum += value;
weightedSum += (value * weight);
totalWeight += weight;
}
if (numItems > 0 && totalWeight > 0) {
printf("%.2lf %.2lf\n", totalSum / numItems, weightedSum / totalWeight);
} else {
// Handle cases where numItems or totalWeight is zero to avoid division by zero
// For simplicity, we might print 0.0 0.0 or an error message
printf("0.00 0.00\n");
}
return 0;
}
Este programa calcula a média simples e a média ponderada de um conjunnto de números. Ele lê a quantidade de itens, e para cada item, lê um valer e seu peso correspondente. A saída são duas médias formatadas com duas casas decimais.
Acumulador Condicional
#include <stdio.h>
int main() {
int n;
long long currentSum;
scanf("%d %lld", &n, ¤tSum);
int count = 0;
for (int i = 0; i < n; ++i) {
long long value;
scanf("%lld", &value);
if (value + currentSum <= 0) {
continue;
}
currentSum += value;
count++;
}
printf("%d %lld\n", count, currentSum);
return 0;
}
Este código itera sobre uma série de números, adicionando-os a uma soma inicial currentSum apenas se a soma resultante não for negativa ou zero. Ele conta quantos números foram efetivamente adicionados e exibe a contagem final e a soma acumulada.
Detecção de Caractere Específico
#include <stdio.h>
int main() {
int limit;
int foundB = 0; // Flag to indicate if 'b' is found
char currentChar;
scanf("%d", &limit);
// Consume the newline character after reading the integer
currentChar = getchar();
for (int i = 0; i < limit; ++i) {
currentChar = getchar();
if (currentChar == 'b') {
foundB = 1;
}
}
if (foundB) {
printf("CVBB\n");
} else {
printf("CVB");
}
return 0;
}
Este programa lê um número limit e, em seguida, lê limit caracteres. Se o caractere 'b' for encontrado em qualquer um desses caracteres lidos, ele imprime "CVBB"; caso contrário, imprime "CVB".
Distância de Ponto a Plano
#include <stdio.h>
#include <math.h>
#define REAL double
int main() {
REAL a, b, c, d;
scanf("%lf %lf %lf %lf", &a, &b, &c, &d);
REAL pX, pY, pZ;
// Expecting input like (x,y,z)
scanf(" (%lf,%lf,%lf)", &pX, &pY, &pZ);
// The formula for the distance from a point (x0, y0, z0) to a plane Ax + By + Cz + D = 0 is |Ax0 + By0 + Cz0 + D| / sqrt(A^2 + B^2 + C^2)
REAL numerator = a * pX + b * pY + c * pZ + d;
numerator = fabs(numerator); // Absolute value
REAL denominator = a * a + b * b + c * c;
denominator = sqrt(denominator);
if (denominator == 0) {
// Handle the case where the plane coefficients are all zero (not a valid plane)
printf("Invalid plane definition.\n");
} else {
printf("%.4lf\n", numerator / denominator);
}
return 0;
}
Este código calcula a distância perpendicular de um ponto 3D a um plano definido pela equação Ax + By + Cz + D = 0. Ele lê os coeficientes do plano e as coordenadas do ponto, aplicando a fórmula da distância e imprimindo o resultado com quatro casas decimais.
Identificar Participantes com Pontuação Suficiente
#include <stdio.h>
int main() {
int totalParticipants;
// Stores indices (positions) of participants who scored 1 in the first part
int part1Indices[1001];
// Stores the sum of scores from the second part for corresponding participants
int part2Scores[1001] = {0};
int part1Count = 0; // Counter for participants who scored 1 in the first part
scanf("%d", &totalParticipants);
// First pass: Identify participants scoring 1 in the first part
for (int i = 0; i < totalParticipants; ++i) {
int scorePart1;
scanf("%d", &scorePart1);
if (scorePart1 == 1) {
part1Count++;
part1Indices[part1Count] = i + 1; // Store 1-based index
part2Scores[part1Count] = 0; // Initialize score for part 2
}
}
// Second pass: Read scores from the second part for those identified
for (int i = 1; i <= part1Count; ++i) {
int scorePart2Temp;
// Read three scores for the second part
for (int j = 0; j < 3; ++j) {
scanf("%d", &scorePart2Temp);
part2Scores[i] += scorePart2Temp;
}
}
printf("Resposta:");
// Third pass: Check and print indices of participants with final score >= 2
for (int i = 1; i <= part1Count; ++i) {
if (part2Scores[i] >= 2) {
printf("%d ", part1Indices[i]);
}
}
printf("\n"); // Ensure a newline at the end
return 0;
}
Este programa processa resultados de duas partes. Ele primeiro identifica os participantes que obtiveram nota 1 na primeira parte. Em seguida, para esses participantes, ele lê três notas da segunda parte e calcula a soma. Finalmente, ele imprime os índices (posições originais) dos participantes cuja soma das notas da segunda parte é de pelo menos 2.
Menor Distância entre Dois Pontos Relativos
#include <stdio.h>
#include <math.h>
#define REAL double
int main() {
REAL xA, yA, xB, yB;
scanf("%lf %lf %lf %lf", &xA, &yA, &xB, &yB);
REAL targetX, targetY;
// Expecting input format like (x,y)
scanf(" (%lf,%lf)", &targetX, &targetY);
// Calculate distance from target point to point A
REAL distToA = sqrt(pow(targetX - xA, 2) + pow(targetY - yA, 2));
// Calculate distance from target point to point B
REAL distToB = sqrt(pow(targetX - xB, 2) + pow(targetY - yB, 2));
printf("%.2lf\n", fmin(distToA, distToB));
return 0;
}
Estee código determina qual de dois pontos (A ou B) está mais próximo de um terceiro ponto alvo. Ele calcula a distância euclidiana entre o ponto alvo e cada um dos pontos A e B, e então imprime a menor dessas duas distâncias com duas casas decimais.
Classificação de Ponto em Relação a um Retângulo
#include <stdio.h>
#include <math.h> // For fmax and fmin
// Helper function to check if a value 'n' is within the range [minVal, maxVal]
// Returns -1 if outside, 0 if on the boundary, 1 if strictly inside
int checkBounds(int maxVal, int minVal, int n) {
if (n < minVal || n > maxVal) return -1; // Outside the range
if (n == minVal || n == maxVal) return 0; // On the boundary
return 1; // Strictly inside
}
int main() {
int x1, y1, z1; // Coordinates of the first corner of the bounding box
scanf("%d %d %d", &x1, &y1, &z1);
int x2, y2, z2; // Coordinates of the opposite corner of the bounding box
scanf("%d %d %d", &x2, &y2, &z2);
// Determine the actual min and max for each dimension
int maxX = fmax(x1, x2);
int minX = fmin(x1, x2);
int maxY = fmax(y1, y2);
int minY = fmin(y1, y2);
int maxZ = fmax(z1, z2);
int minZ = fmin(z1, z2);
int numPoints;
scanf("%d", &numPoints);
for (int i = 0; i < numPoints; ++i) {
int pX, pY, pZ;
scanf("%d %d %d", &pX, &pY, &pZ);
// Check each dimension
int checkX = checkBounds(maxX, minX, pX);
int checkY = checkBounds(maxY, minY, pY);
int checkZ = checkBounds(maxZ, minZ, pZ);
// If any dimension is outside, the point is "Outer"
if (checkX == -1 || checkY == -1 || checkZ == -1) {
printf("Outer\n");
continue;
}
// Sum the results of the bounds checks. If sum is 3, it means it was strictly inside all dimensions.
// If sum is less than 3, it means at least one dimension was on the boundary.
int sumChecks = checkX + checkY + checkZ;
if (sumChecks < 3) {
printf("Edge\n");
continue;
}
// If not Outer and not Edge, it must be "Inner"
printf("Inner\n");
}
return 0;
}
Este programa classifica pontos 3D em relação a um paralelepípedo definido por dois vértices opostos. Para cada ponto de teste, ele determina se está "Outer" (fora), "Edge" (na superfície/borda) ou "Inner" (dentro) do paralelepípedo, imprimindo a classificação correspondente.