
Matheus Maldi
Membro Pleno-
Posts
541 -
Cadastrado em
-
Última visita
Tipo de conteúdo
Artigos
Selos
Livros
Cursos
Análises
Fórum
Tudo que Matheus Maldi postou
-
Para usar o primeiro código, você precisaria de um construtor, por que a string Name precisa ser inicializada, assim public class Usuário { public string Nome { get; set; } public int Idade { get; set; } public Usuário(string nome, int idade) { Nome = nome; Idade = idade; } public void Apresentar() { Console.WriteLine($"Olá, meu nome é {Nome} e minha idade é {Idade}"); } } Que pode ser simplificado desta forma public class Usuário(string Nome, int Idade) { public void Apresentar() { Console.WriteLine($"Olá, meu nome é {Nome} e minha idade é {Idade}"); } }
-
Pelo que vi o link está ensinando sistema operacional de 16 bits para x86, deve ser esse o problema Segue um outro link https://wiki.osdev.org/Bare_Bones#Writing_a_kernel_in_C
-
C Depurador não funciona ao usar biblioteca <math.h>.
Matheus Maldi respondeu ao tópico de beggarjs em C/C#/C++
No linux para user math.h você precisa adicionar a flag -lm gcc main.c -lm No meu VSCode ele gerou um arquivo ./vscode/tasks.json assim { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } -
C Algorítimo em C com um loop while que conte de 1 a 3.000.000, de 1 em 1.
Matheus Maldi respondeu ao tópico de Thmpv em C/C#/C++
Com o relógio. #include <stdio.h> #include <time.h> int main() { int contador = 0; struct timespec start, stop; clock_gettime(CLOCK_REALTIME, &start); while (contador < 3000000) { ++contador; printf("\r%d", contador); if ((contador % 1000000) == 0) { clock_gettime(CLOCK_REALTIME, &stop); double elapsed = ((stop.tv_sec - start.tv_sec) * 1e6 + (stop.tv_nsec - start.tv_nsec) / 1e3) / 1e6; printf("\t%d em %lfsec\n", contador, elapsed); } } return 0; } -
const char *funcao(int numero) { if (numero % 2 == 0) return "par"; else return "impar"; } ... printf("%s\n", funcao(10)); ... é isso que quer fazer
-
C Gerar valores aleatórios sem repetição em uma matriz
Matheus Maldi respondeu ao tópico de GabrielPinheiroamd em C/C#/C++
O problema eh que usei malloc sem iniciar todos os campos, na maioria das vezes o malloc entrega a memória já zerada principalmente quando alocamos pouco espaço, mas as vezes nem com lixo. -
C Gerar valores aleatórios sem repetição em uma matriz
Matheus Maldi respondeu ao tópico de GabrielPinheiroamd em C/C#/C++
Referente ao malloc e calloc eu SEMPRE uso o calloc, vou contar um motivo, uma vez estava escrevendo um PERFT, e para escrever um desses é normal escrever muitos testes, assim é fácil detectar quando uma alteração código quebrar, depois de uma certa complexidade do código acontecia algo estranho, se eu mandasse executar o código 10 vezes em 9 passava e 1 quebrava, o mesmo binário. Foi mais de um dia procurando e o problema era no malloc, pelo motivo de eu esquecer de iniciar todos os campos. Não vale a pena nenhum ganho de performance que talvez exista na chamada das funções. Referente aos asserts, como você mesmo disse, não estamos desenvolvendo nada definitivo, apenas um exemplo de código para se ler em 2 minutos. -
C Gerar valores aleatórios sem repetição em uma matriz
Matheus Maldi respondeu ao tópico de GabrielPinheiroamd em C/C#/C++
Segue um exemplo de um sorteio: #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <time.h> int *sorteia_seed(int min, int max, unsigned int seed) { assert(min < max); int len = max - min + 1; int *result = calloc(len, sizeof(int)); for (int i = 0, val = min; i < len; i++, val++) result[i] = val; srand(seed); for (int i = 0; i < len; i++) { int random_index = rand() % len; int tmp = result[i]; result[i] = result[random_index]; result[random_index] = tmp; } return result; } int *sorteia(int min, int max) { return sorteia_seed(min, max, time(NULL)); } int main() { int *numeros = sorteia(1, 60); for (int i = 0; i < 6; i++) printf("%d, ", numeros[i]); printf("\n"); free(numeros); return 0; } -
C Erro ao compilar terminal ubuntu, erro : referencia indefinida para GetInt.
Matheus Maldi respondeu ao tópico de Fellipe Queiroz em C/C#/C++
Está faltando você incluir a lib cc50, não sei por onde está estudando, mas recomendaria usar o lib cs50 de harvard https://github.com/cs50/libcs50 -
C Onde consigo um codigo fonte em C de Jogo de Xadrez?
Matheus Maldi respondeu ao tópico de PowerGraphics em C/C#/C++
Existe a engine Cfish, a implementação do Stockfish em c https://github.com/syzygy1/Cfish -
for (float f = 0.25; f < 3.99; f += 0.25) printf("%.2f\t", f); Veja se isso resolve
-
C++ Pesquisar na Internet em c++ e colocar em um banco SQL
Matheus Maldi respondeu ao tópico de Marcos Salabert Settimi em C/C#/C++
Recomendaria pesquisar sobre Selenium e WebDriver, talvez essa lib ajude: https://github.com/sekogan/webdriverxx Sobre o banco de dados, procure qualquer um. -
C Como pegar o resto da divisao sem usar o %
Matheus Maldi respondeu ao tópico de ProgramadorInsano em C/C#/C++
#include <assert.h> int resto(int x, int mod) { assert(mod > 0); while (x > mod) x -= mod; return x; } int resto_recursiva(int x, int mod) { assert(mod > 0); if (x > mod) return resto_recursiva(x - mod, mod); return x; } int main() { assert(resto(10, 3) == 1); assert(resto(10, 4) == 2); assert(resto(10, 11) == 10); assert(resto_recursiva(10, 3) == 1); assert(resto_recursiva(10, 4) == 2); assert(resto_recursiva(10, 11) == 10); return 0; } -
Sem o código fica difícil, mas não iria analisar seu código, rbtree é difícil. Vou deixar a minha implementação // rbtree.h #ifndef _RBTREE_H_ #define _RBTREE_H_ #if __cplusplus extern "C" { #endif #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <errno.h> #define BLACK (true) #define RED (false) typedef int (*compare_func)(const void*, const void*); typedef int rbtree_status; struct rbnode { bool color; struct rbnode* left; struct rbnode* right; struct rbnode* parent; }; struct rbtree { struct rbnode* root; size_t element_size; size_t length; compare_func cmp; }; void rbtree_ctor (struct rbtree* tree, size_t element_size, compare_func cmp); void rbtree_dtor (struct rbtree* tree); size_t rbtree_length (struct rbtree* tree); void* rbtree_lookup (struct rbtree* tree, void* element); rbtree_status rbtree_insert (struct rbtree* tree, void* element); void rbtree_delete (struct rbtree* tree, void* element); static inline bool rbnode_color(struct rbnode* node) { return node == NULL ? BLACK : node->color; } static inline void* rbnode_get_data_address(struct rbnode* node) { return &node[1]; } static struct rbnode* rbnode_new(size_t element_size, void* element) { struct rbnode* node = (struct rbnode*)calloc(1, sizeof(struct rbnode) + element_size); if (node == NULL) return NULL; void* target = rbnode_get_data_address(node); memcpy(target, element, element_size); return node; } static void rbnode_free(struct rbnode* node) { if (node != NULL) { rbnode_free(node->left); rbnode_free(node->right); free(node); } } static inline struct rbnode* rbnode_grandparent(struct rbnode* node) { return node->parent->parent; } static inline struct rbnode* rbnode_sibling(struct rbnode* node) { return node == node->parent->left ? node->parent->right : node->parent->left; } static inline struct rbnode* rbnode_uncle(struct rbnode* node) { return rbnode_sibling(node->parent); } static struct rbnode* rbnode_maximum(struct rbnode* node) { while (node->right != NULL) node = node->right; return node; } static inline struct rbnode* rbnode_lookup(struct rbtree* tree, void* element, compare_func cmp) { struct rbnode* node = tree->root; while (node != NULL) { int result = cmp(element, rbnode_get_data_address(node)); if (result == 0) return node; else if (result < 0) node = node->left; else node = node->right; } return node; } static inline void replace_node(struct rbtree* tree, struct rbnode* old_node, struct rbnode* new_node) { if (old_node->parent == NULL) tree->root = new_node; else if (old_node == old_node->parent->left) old_node->parent->left = new_node; else old_node->parent->right = new_node; if (new_node != NULL) new_node->parent = old_node->parent; } static inline void rotate_left(struct rbtree* tree, struct rbnode* node) { struct rbnode* right = node->right; replace_node(tree, node, right); node->right = right->left; if (right->left != NULL) right->left->parent = node; right->left = node; node->parent = right; } static inline void rotate_right(struct rbtree* tree, struct rbnode* node) { struct rbnode* left = node->left; replace_node(tree, node, left); node->left = left->right; if (left->right != NULL) left->right->parent = node; left->right = node; node->parent = left; } static void insert_case_1(struct rbtree* tree, struct rbnode* node); static void insert_case_2(struct rbtree* tree, struct rbnode* node); static void insert_case_3(struct rbtree* tree, struct rbnode* node); static void insert_case_4(struct rbtree* tree, struct rbnode* node); static void insert_case_5(struct rbtree* tree, struct rbnode* node); static void insert_case_1(struct rbtree* tree, struct rbnode* node) { if (node->parent == NULL) node->color = BLACK; else insert_case_2(tree, node); } static void insert_case_2(struct rbtree* tree, struct rbnode* node) { if (rbnode_color(node->parent) == BLACK) return; else insert_case_3(tree, node); } static void insert_case_3(struct rbtree* tree, struct rbnode* node) { if (rbnode_color(rbnode_uncle(node)) == RED) { node->parent->color = BLACK; rbnode_uncle(node)->color = BLACK; rbnode_grandparent(node)->color = RED; insert_case_1(tree, rbnode_grandparent(node)); } else insert_case_4(tree, node); } static void insert_case_4(struct rbtree* tree, struct rbnode* node) { if (node == node->parent->right && node->parent == rbnode_grandparent(node)->left) { rotate_left(tree, node->parent); node = node->left; } else if (node == node->parent->left && node->parent == rbnode_grandparent(node)->right) { rotate_right(tree, node->parent); node = node->right; } insert_case_5(tree, node); } static void insert_case_5(struct rbtree* tree, struct rbnode* node) { node->parent->color = BLACK; rbnode_grandparent(node)->color = RED; if (node == node->parent->left && node->parent == rbnode_grandparent(node)->left) rotate_right(tree, rbnode_grandparent(node)); else rotate_left(tree, rbnode_grandparent(node)); } void rbtree_ctor(struct rbtree* tree, size_t element_size, compare_func cmp) { tree->root = NULL; tree->element_size = element_size; tree->length = 0; tree->cmp = cmp; } void rbtree_dtor(struct rbtree* tree) { rbnode_free(tree->root); } size_t rbtree_length(struct rbtree* tree) { return tree->length; } rbtree_status rbtree_insert(struct rbtree* tree, void* element) { struct rbnode* inserted_node = rbnode_new(tree->element_size, element); if (inserted_node == NULL) return ENOMEM; if (tree->root == NULL) tree->root = inserted_node; else { struct rbnode* n = tree->root; while (true) { void* target = rbnode_get_data_address(n); int result = tree->cmp(element, target); if (result == 0) { rbnode_free(inserted_node); memcpy(target, element, tree->element_size); return EXIT_SUCCESS; } else if (result < 0) { if (n->left == NULL) { n->left = inserted_node; break; } else n = n->left; } else { if (n->right == NULL) { n->right = inserted_node; break; } else n = n->right; } } inserted_node->parent = n; } insert_case_1(tree, inserted_node); tree->length++; return EXIT_SUCCESS; } void* rbtree_lookup(struct rbtree* tree, void* element) { struct rbnode* node = rbnode_lookup(tree, element, tree->cmp); return node == NULL ? NULL : rbnode_get_data_address(node); } static void delete_case1(struct rbtree* tree, struct rbnode* node); static void delete_case2(struct rbtree* tree, struct rbnode* node); static void delete_case3(struct rbtree* tree, struct rbnode* node); static void delete_case4(struct rbtree* tree, struct rbnode* node); static void delete_case5(struct rbtree* tree, struct rbnode* node); static void delete_case6(struct rbtree* tree, struct rbnode* node); void rbtree_delete(struct rbtree* tree, void* element) { struct rbnode* node = rbnode_lookup(tree, element, tree->cmp); if (node == NULL) return; if (node->left != NULL && node->right != NULL) { struct rbnode* pred = rbnode_maximum(node->left); memcpy(rbnode_get_data_address(node), rbnode_get_data_address(pred), tree->element_size); node = pred; } struct rbnode* child = node->right == NULL ? node->left : node->right; if (rbnode_color(node) == BLACK) { node->color = rbnode_color(child); delete_case1(tree, node); } replace_node(tree, node, child); if (node->parent == NULL && child != NULL) child->color = BLACK; free(node); tree->length--; } static void delete_case1(struct rbtree* tree, struct rbnode* node) { if (node->parent == NULL) return; else delete_case2(tree, node); } static void delete_case2(struct rbtree* tree, struct rbnode* node) { if (rbnode_color(rbnode_sibling(node)) == RED) { node->parent->color = RED; rbnode_sibling(node)->color = BLACK; if (node == node->parent->left) rotate_left(tree, node->parent); else rotate_right(tree, node->parent); } delete_case3(tree, node); } static void delete_case3(struct rbtree* tree, struct rbnode* node) { if (rbnode_color(node->parent) == BLACK && rbnode_color(rbnode_sibling(node)) == BLACK && rbnode_color(rbnode_sibling(node)->left) == BLACK && rbnode_color(rbnode_sibling(node)->right) == BLACK) { rbnode_sibling(node)->color = RED; delete_case1(tree, node->parent); } else delete_case4(tree, node); } static void delete_case4(struct rbtree* tree, struct rbnode* node) { if (rbnode_color(node->parent) == RED && rbnode_color(rbnode_sibling(node)) == BLACK && rbnode_color(rbnode_sibling(node)->left) == BLACK && rbnode_color(rbnode_sibling(node)->right) == BLACK) { rbnode_sibling(node)->color = RED; node->parent->color = BLACK; } else delete_case5(tree, node); } static void delete_case5(struct rbtree* tree, struct rbnode* node) { if (node == node->parent->left && rbnode_color(rbnode_sibling(node)) == BLACK && rbnode_color(rbnode_sibling(node)->left) == RED && rbnode_color(rbnode_sibling(node)->right) == BLACK) { rbnode_sibling(node)->color = RED; rbnode_sibling(node)->left->color = BLACK; rotate_right(tree, rbnode_sibling(node)); } else if (node == node->parent->right && rbnode_color(rbnode_sibling(node)) == BLACK && rbnode_color(rbnode_sibling(node)->right) == RED && rbnode_color(rbnode_sibling(node)->left) == BLACK) { rbnode_sibling(node)->color = RED; rbnode_sibling(node)->right->color = BLACK; rotate_left(tree, rbnode_sibling(node)); } delete_case6(tree, node); } static void delete_case6(struct rbtree* tree, struct rbnode* node) { rbnode_sibling(node)->color = rbnode_color(node->parent); node->parent->color = BLACK; if (node == node->parent->left) { rbnode_sibling(node)->right->color = BLACK; rotate_left(tree, node->parent); } else { rbnode_sibling(node)->left->color = BLACK; rotate_right(tree, node->parent); } } #if __cplusplus } #endif #endif Exemplo de uso para seus números: #include "include/rbtree.h" int intcmp(const void *vl, const void *vr) { int lhs = *(int*)vl; int rhs = *(int*)vr; if (lhs > rhs) return 1; if (lhs < rhs) return -1; return 0; } void walk_node(struct rbnode *node, int depth) { if (node) { walk_node(node->left, depth + 1); int node_value = *(int*)rbnode_get_data_address(node); printf("Profundidade %d: %d\n", depth, node_value); walk_node(node->right, depth + 1); } } void walk_tree(struct rbtree *tree) { walk_node(tree->root, 0); } int main() { struct rbtree tree; rbtree_ctor(&tree, sizeof(int), intcmp); #define VET_LEN 8 int vet[VET_LEN] = { 6, 4, 3, 2, 1, 5, 7, 8 }; for (int i = 0; i < VET_LEN; i++) rbtree_insert(&tree, &vet[i]); walk_tree(&tree); // 4 // 2 6 // 1 3 5 7 // 8 rbtree_dtor(&tree); return 0; } E teste da minha implementação da arvore #include <assert.h> #include "rbtree.h" int intcmp(const void *vl, const void *vr) { int lhs = *(int*)vl; int rhs = *(int*)vr; if (lhs > rhs) return 1; if (lhs < rhs) return -1; return 0; } // 1. Each node is either red or black. static void verify_property_1(struct rbnode* node); // 2. The root is black static void verify_property_2(struct rbnode* root); // 3. All leaves (NULL) are black. static void verify_property_3(); // 4. If a node is red, then both its children are black. static void verify_property_4(struct rbnode* node); // 5. Every path from a given node to any of its descendant // NULL nodes goes through the same number of black nodes. static void verify_property_5_helper(struct rbnode* node, int black_count, int* path_black_count); static void verify_property_5(struct rbnode* root); static void verify_properties(struct rbtree* tree); int main() { struct rbtree tree; rbtree_ctor(&tree, sizeof(int), intcmp); verify_properties(&tree); size_t len = 0; for (int i = 0; i < 100; i += 2) { rbtree_insert(&tree, &i); verify_properties(&tree); len++; } assert(rbtree_length(&tree) == len); for (int i = 99; i > 0; i -= 2) { rbtree_insert(&tree, &i); verify_properties(&tree); len++; } assert(rbtree_length(&tree) == len); for (int i = 99; i >= 0; i--) { rbtree_delete(&tree, &i); len--; } assert(rbtree_length(&tree) == len); rbtree_dtor(&tree); return 0; } // 1. Each node is either red or black. static void verify_property_1(struct rbnode* node) { assert(rbnode_color(node) == RED || rbnode_color(node) == BLACK); if (node == NULL) return; verify_property_1(node->left); verify_property_1(node->right); } // 2. The root is black static void verify_property_2(struct rbnode* root) { assert(rbnode_color(root) == BLACK); } // 3. All leaves (NULL) are black. static void verify_property_3() { struct rbnode* node = NULL; assert(rbnode_color(node) == BLACK); } // 4. if a node is red, then both its children are black. static void verify_property_4(struct rbnode* node) { if (rbnode_color(node) == RED) { assert (rbnode_color(node->left) == BLACK); assert (rbnode_color(node->right) == BLACK); assert (rbnode_color(node->parent) == BLACK); } if (node == NULL) return; verify_property_4(node->left); verify_property_4(node->right); } // 5. Every path from a given node to any of its descendant // NULL nodes goes through the same number of black nodes. static void verify_property_5_helper(struct rbnode* node, int black_count, int* path_black_count) { if (rbnode_color(node) == BLACK) black_count++; if (node == NULL) { if (*path_black_count == -1) *path_black_count = black_count; else assert(black_count == *path_black_count); return; } verify_property_5_helper(node->left, black_count, path_black_count); verify_property_5_helper(node->right, black_count, path_black_count); } // 5. Every path from a given node to any of its descendant // NULL nodes goes through the same number of black nodes. static void verify_property_5(struct rbnode* root) { int black_count_path = -1; verify_property_5_helper(root, 0, &black_count_path); } static void verify_properties(struct rbtree* tree) { verify_property_1(tree->root); verify_property_2(tree->root); verify_property_3(); verify_property_4(tree->root); verify_property_5(tree->root); } Está arvore foi escrita com base neste código: https://web.archive.org/web/20140328232325/http://en.literateprograms.org/Red-black_tree_(C)
-
C Olá ! Como seria essas questões usando alocação dinâmica
Matheus Maldi respondeu ao tópico de Cynthia Moreira em C/C#/C++
Seria algo assim void retira(int *vec, size_t vec_len, size_t index) { assert(index < vec_len); // Mova todos os caracteres a partir (index + 1) um indice atras // realloc o vetor para o tamanho sizeof(int) * (vec_len - 1) } char* strcat_new(const char* s0, const char* s1) { // pegue o valor da string s0 // pegue o valor da string s1 // crie um variavel para guardar o valor do tamanho da string nove // este valor será a soma das string + 2 (espaço e nulo no final) // alloque a memoria // concatene neste ponteiro a s0 depois o espaço de depois a s1 e depois o '\0' // retorne o ponteiro } -
C++ Exercício de MDC. Linguagem C / C++.
Matheus Maldi respondeu ao tópico de Ricardo_Nascimento em C/C#/C++
Segue uma solução simples em C #include <assert.h> #include <stdio.h> int mdc(int *v, size_t len) { assert(len != 0); int ret = v[0]; for (size_t i = 1; i < len; i++) { int b = v[i]; while (b != 0) { int r = ret % b; ret = b; b = r; } } return ret; } int main() { int v[] = { 2, 4, 6, 8, 10, 12, 14 }; printf("Mdc: %d\n", mdc(v, 7)); return 0; } Ou para o insano C++ #include <iostream> #include <vector> #include <cassert> #include <iterator> using namespace std; template<typename Iterator> typename std::iterator_traits<Iterator>::value_type mdc(Iterator begin, Iterator end) { assert(begin < end); using value_type = typename std::iterator_traits<Iterator>::value_type; Iterator it = begin; value_type ret = *it++; while(it != end) { value_type b = *it++; while (b != 0) { value_type r = ret % b; ret = b; b = r; } } return ret; } int mdc(vector<int> v) { mdc(v.begin(), v.end()); } int main() { std::cout << mdc({2, 4, 6, 8, 10, 12, 14 }) << std::endl; return 0; } -
Você não esta pegando o pivô, inicie a variável com um valor entre o inicio e o fim, normalmente o pessoal usa: int pivo = (inicio + final) / 2; Isso deve resolver o problema do seu algoritmo.
-
C Programa para dizer se é inteiro ou decimal
Matheus Maldi respondeu ao tópico de Joel Martins em C/C#/C++
Cuidado com o uso de ponto flutuante fazendo casting para inteiros, isso vai gerar problemas / #include <stdio.h> #include <stdbool.h> #include <math.h> bool float_is_integer(float f, float epsilon) { if (fabsf(roundf(f) - f) <= epsilon) return true; return false; } int main() { // 3 == (3 ^ (1/20)) ^ 20 float tres = powf(powf(3.0f, 0.05f), 20.0f); // Está conta retorna deve retornar 3 if (float_is_integer(tres, 0.00001f)) printf("%.0f\n", tres); else printf("Nao eh inteiro\n"); return 0; } A conta acima matematicamente tem resultado 3, mas se efetuar a conta com ponto flutuante vai retornar 2.9999992847, portanto a função permite você adicionar uma margem de erro (paramentro epsilon). -
Bom, efetuei uma estrutura para cartas e baralho #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <assert.h> struct carta { uint8_t id; }; struct baralho { struct carta cartas[52]; }; void carta_display(struct carta *carta) { assert(carta->id < 52); const char* naipe[4] = { "Paus", "Ouros", "Copas", "Espadas" }; const char* numeros[13] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Valete", "Dama", "Rei" }; printf("%s %s\n", numeros[carta->id % 13], naipe[carta->id / 13]); } void baralho_ctor(struct baralho* baralho) { for (int i = 0; i < 52; i++) baralho->cartas[i].id = i; } void baralho_embaralhar(struct baralho* baralho) { // faça o seed para o random for (int i = 0; i < 52; i++) { int r = rand() % 52; struct carta tmp = baralho->cartas[i]; baralho->cartas[i] = baralho->cartas[r]; baralho->cartas[r] = tmp; } } int main() { struct baralho b; baralho_ctor(&b); baralho_embaralhar(&b); for (int i = 0; i < 52; i++) carta_display(&b.cartas[i]); return 0; } Note que nao efetuei o seed para o random, então sempre vai embaralhar no mesmo jeito
-
Verifique esse código, ele é bem simples, e imprime um baralho: #include <stdio.h> #include <stdint.h> #include <assert.h> void carta_display(uint8_t id) { assert(id < 52); const char* naipe[4] = { "Paus", "Ouros", "Copas", "Espadas" }; const char* numeros[13] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Valete", "Dama", "Rei" }; printf("%s %s\n", numeros[id % 13], naipe[id / 13]); } int main() { for (int i = 0; i < 52; i++) carta_display(i); return 0; }
-
Bom, verifique este codigo: union { uint32_t u; uint16_t u16[2]; } dst; dst.u16[0] = 50938; dst.u16[1] = 1; printf("dst u16[0]: %u\n", dst.u16[0]); // 50938 printf("dst u16[1]: %u\n", dst.u16[1]); // 1 printf("dst: %u\n", dst.u); // 116474 Faz funcionar conforme disse
-
Bom, então deve ser este o caso: https://pt.wikipedia.org/wiki/Extremidade_(ordenação) Acredito então que deve ser assim a leitura: uint32_t be_to_le(uint32_t be) { union { uint32_t u; uint8_t u8[4]; } src, dst; src.u = be; for (int i = 0, e = 3; i < 4; i++, e--) dst.u8[i] = src.u8[e]; return dst.u; } Se puder mandar os exemplos de inteiros lidos e seus reais valores
-
Como o @Flávio Pedroza mostrou, você pode ser o lo e depois o hi e juntar uint32_t parse_lo_hi(uint16_t lo, uint16_t hi) { return (uint32_t)lo + ((uint32_t)hi << 16); } Agora se não é possível ler as partes separadas, somente os 32 bits use: uint32_t lohi_to_hilo(uint32_t lohi) { uint32_t lo = lohi >> 16; uint32_t hi = lohi << 16; return lo + hi; }
-
C Sacar valores R$11, 00, R$13, 00, R$16,00 e R$18, 00 no caixa eletrônico
Matheus Maldi respondeu ao tópico de ArieviloAgarf em C/C#/C++
Problema interessante resolvi tratando os casos com 7, 9, 11, 13, 6 e 8 #include <stdio.h> #include <assert.h> struct saque { int valor; union { int notas[6]; struct { int notas_100, notas_50, notas_20, notas_10, notas_5, notas_2; }; }; }; void sacar_7(struct saque* s) { assert(s->valor % 10 == 7); s->valor -= 7; s->notas_2 += 1; s->notas_5 += 1; } void sacar_9(struct saque* s) { assert(s->valor % 10 == 9); s->valor -= 9; s->notas_2 += 2; s->notas_5 += 1; } void sacar_11(struct saque* s) { assert(s->valor >= 11 && s->valor % 10 == 1); s->valor -= 11; s->notas_2 += 3; s->notas_5 += 1; } void sacar_13(struct saque* s) { assert(s->valor >= 13 && s->valor % 10 == 3); s->valor -= 13; s->notas_2 += 4; s->notas_5 += 1; } void sacar_6_ou_8(struct saque* s) { assert(s->valor % 10 == 6 || s->valor % 10 == 8); int n_notas = (s->valor % 10) / 2; s->valor -= (n_notas * 2); s->notas_2 += n_notas; } void sacar_restante(struct saque* s) { // implemente o saque restante } int main() { int valor; scanf("%d", &valor); assert(valor > 1 && valor != 3); struct saque s = { valor, 0, 0, 0, 0, 0, 0 }; if (s.valor % 10 == 1) sacar_11(&s); else if (s.valor % 10 == 3) sacar_13(&s); else if (s.valor % 10 == 7) sacar_7(&s); else if (s.valor % 10 == 9) sacar_9(&s); else if (s.valor % 10 == 6 || s.valor % 10 == 8) sacar_6_ou_8(&s); sacar_restante(&s); printf("Saque no valor: %d\n", valor); printf("Notas 100: %d\n", s.notas_100); printf("Notas 50: %d\n", s.notas_50); printf("Notas 20: %d\n", s.notas_20); printf("Notas 10: %d\n", s.notas_10); printf("Notas 5: %d\n", s.notas_5); printf("Notas 2: %d\n", s.notas_2); return 0; } -
ASP.NET Projeto não abre no localhost
Matheus Maldi respondeu ao tópico de Samuel.ms2112 em Programação - outros
Esta acessando a porta 5000?
Sobre o Clube do Hardware
No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais
Direitos autorais
Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais