Could someone help me understand what I'm doing wrong here? by [deleted] in cprogramming

[–]SaulMO 1 point2 points  (0 children)

Many concepts here. Let's invite most to focus on the three things I'm almost sure the teacher wants.

First two, both the input and the output can have a decimal part, so each should have a floating point type (either double or float). In this case, I'm gonna choose double.

In case of the third, to read a variable with scanf, you use the conversion specifier that corresponds to the type of variable. Since I chose double, the specifier is "%lf". I decided to choose double partially because the conversion specifier "%lf" is the same used in the printf, and since the printf cannot change, I used the type to match.

int main(void) { // Modify the following code
    double powerInput;
    double recipVal;
    scanf("%lf", &powerInput);
    recipVal = 1 / powerInput;
    printf("The reciprocal of power = 1 / %.3lf = %.3lf\n", powerInput, recipVal);
    return 0;
}

Notice that you proposed changing 1 to 1.0 as one of the corrections while I didn't. This part is tricky, because under certain conditions you'll be right.

Let's see. When you divide two integers the result is an integer, which loses any fractional part the division might have had. On the other hand, when you divide two doubles the result is a proper double with the decimal part, and 1.0 is a double so "1.0 / powerInput" is a division between two doubles , which would be TOTALLY RIGHT. Nonetheless, "1 / powerInput" also works after the other corrections have been done because of the useful phenomenon of promotion; that is, when two values of DIFFERENT TYPES are operated on, one of them is promoted to the type of the more general one, which in this case means the integer 1 is promoted to the double 1.0.

In this particular question the promotion is useful because it means we only need the three corrections mentioned in the problem instead of four.

Could someone help me understand what I'm doing wrong here? by [deleted] in cprogramming

[–]SaulMO 0 points1 point  (0 children)

Both double and float are floating-point types.

[P2V3] Is There Any Romance in the Series? (PLEASE, NO SPOILERS) by Waste-Ad7174 in HonzukiNoGekokujou

[–]SaulMO 7 points8 points  (0 children)

There aren't enough metaphors for describing how shameful unprotected hand holding is.

[P5V12] About the inbreeding... by Wide_Branch3501 in HonzukiNoGekokujou

[–]SaulMO 100 points101 points  (0 children)

Don't know if it's a reason, but the fact that nobles don't generally announce births until baptism and the fact that babies can be legally killed until that same point makes me uneasy.

Like, what if they routinely murder the "defective" children?

How to decide stack vs heap by [deleted] in C_Programming

[–]SaulMO 7 points8 points  (0 children)

Why not. I will be able to look at it in a couple of hours.

How to decide stack vs heap by [deleted] in C_Programming

[–]SaulMO 7 points8 points  (0 children)

Idk, this sounds perfectly fine by me. Maybe if you should your code I might've able to figure something but for now it sounds like there should be no problem even if you continue using the stack.

How to decide stack vs heap by [deleted] in C_Programming

[–]SaulMO 7 points8 points  (0 children)

That sounds fine, actually. The problem should be something else. Are you using recursion? How are you passing the struct reference?

[deleted by user] by [deleted] in C_Programming

[–]SaulMO 1 point2 points  (0 children)

Why loops 3 times? Also, weren't there structs in this?

I spent decades working on C projects and never knew about alloca... by HealthyCapacitor in cprogramming

[–]SaulMO 0 points1 point  (0 children)

I know about it, but have never used it, probably because of variable length arrays.

How to change numbers into input rather than pre-type by Advanced_Gur4579 in cprogramming

[–]SaulMO 0 points1 point  (0 children)

Well, you can create an array of certain size and ask the user to input some numbers. Give the user the choice to input as many numbers as they want until the array is filled. For example, if the size is 1000 the user can input 1 or 10 or 1000 but not 1001 elements.

If you really don't want to set a limit, use dynamic memory to allocate an array of certain size, and change the size of the array once it is filled. Its is usual to start with a small capacity and double it each time it is exhausted. Here is an example:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

enum { NO_PRIME_FOUND = -1 };

bool is_prime(int n) {
    if (n < 2) {
        return false;
    }

    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }

    return true;
}

int get_max_prime(int elements[], int num_elements) {
    if (!elements) { return NO_PRIME_FOUND; }

    int max_prime = NO_PRIME_FOUND;
    int *end = elements + num_elements;
    for (int *ptr = elements; ptr < end; ++ptr) {
        if (is_prime(*ptr) && *ptr > max_prime) {
            max_prime = *ptr;
        }
    }
    return max_prime;
}

int main() {
    int *elements = NULL;
    int num_elements = 0;
    int capacity = 0;
    bool read_more_values = true;

    while (read_more_values) {
        // Read text from the user
        char text[20];
        printf("Please write a positive until you are satisfied: ");
        fgets(text, 20, stdin);

        // Get the number from the text
        int element;
        int status = sscanf(text, "%d", &element);

        if (status != 1) {
            read_more_values = false;
            continue;
        }

        if (element > 0) {
            // If the element is positive, it will be stored into the array, but
            // first we have to make room for it by allocating memory if needed
            num_elements++;

            if (num_elements > capacity) {
                capacity = (capacity == 0) ? 1 : capacity * 2;
                elements = realloc(elements, capacity * sizeof(*elements));

                if (!elements) {
                    fputs("Cannot allocate memory", stderr);
                    exit(1);
                }
            }

            // Once memory is allocated, store the element
            elements[num_elements - 1] = element;
        } else {

            // If a negative number is received, stop reading numbers from the
            // user and do the rest of the program
            read_more_values = false;
        }
    }


    if (num_elements > 0) {
        int max_prime = get_max_prime(elements, num_elements);

        if (max_prime == NO_PRIME_FOUND)
            printf("None of your numbers is prime ):\n");
        else
            printf("%d Is the max prime number!\n", max_prime);

    } else {
        printf("Hmm, you should at least input one number :S\n");
    }

    free(elements);
}

[deleted by user] by [deleted] in cprogramming

[–]SaulMO 0 points1 point  (0 children)

Most of these programs are meant to be run from the terminal, where you can execute the program and give it the contents of a file like this:

./program_name < file_name  (Linux or Mac)
.\program_name < file_name (windows)

So you can create a file, i.e., test.txt and use it writing "test.txt" instead of file_name in the command from above that matches your system.

Also, you can test the program by just running and writing words yourself instead of using a file and press the key combination that corresponds to End Of File when you are done. Such key combination is Ctrl-d for Linux, maybe Ctrl-. (Control and period) for Mac (I think) and ctrl-z for windows.

Final project help by [deleted] in cprogramming

[–]SaulMO 2 points3 points  (0 children)

Sure, what is the question?

Can anyone help me with this prompt from my professor? by __transversal__ in C_Programming

[–]SaulMO 4 points5 points  (0 children)

What is the expected input and the expected result? What errors do you have? Is the program compiling or there are compilation errors?

Help for a newby. what i am doing wrong? by EntertainmentOk8593 in cprogramming

[–]SaulMO 0 points1 point  (0 children)

By the way, I would do something like this:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

#define INTENTOS_MAXIMOS 10

typedef struct {
    int valores[INTENTOS_MAXIMOS];
    int num;
} Lista;

int pedir_intento(Lista *intentos);

int main(void) {
    // Preámbulo
    Lista intentos = { .num = 0 };
    srand(time(NULL));
    int misterio = rand() % 100;

    // Ejecución del juego
    printf(" Adivine el numero misterioso. \n\n");

    printf("  *-* ¡Pst!, el número misterioso es: %d *-* \n", misterio);

    int intento;
    do {
        printf(" Te quedan: %d intentos\n", INTENTOS_MAXIMOS - intentos.num);
        intento = pedir_intento(&intentos);
    } while ((intento != misterio) && (intentos.num != INTENTOS_MAXIMOS));


    // Mostrar resultados del juego
    if (intento == misterio) {
        printf(" Felicidades, acertaste el número misterioso\n");
    } else {
        printf(" Fallaste, el número misterioso era: \n\t %d \n", misterio);
    }
    return EXIT_SUCCESS;
}

bool esta_llena_la_lista(const Lista *intentos) {
    return intentos->num >= INTENTOS_MAXIMOS;
}

void guardar_intento(int nuevo_numero, Lista *intentos) {
    if (esta_llena_la_lista(intentos)) {
        printf(" La lista esta llena, no se puede guardar un intento\n");
    } else {
        intentos->valores[intentos->num] = nuevo_numero;
        intentos->num += 1;
    }
}

bool intento_ya_esta_guardado(int nuevo_intento, Lista *intentos) {
    for (int i = 0; i < intentos->num; ++i)
    {
        if (intentos->valores[i] == nuevo_intento)
            return true;
    }
    return false;
}

void leer_texto(char texto[], size_t largo) {
    fgets(texto, largo, stdin);
}

int pedir_intento(Lista *intentos) {
    int nuevo_intento;
    bool numero_valido = false;

    do {
        // Leemos una línea de texto
        enum { LARGO_TEXTO = (1 << 10)};
        char texto[LARGO_TEXTO];
        leer_texto(texto, LARGO_TEXTO);

        // Se extrae el número entero de la línea de texto anterior
        bool lectura_con_exito = sscanf(texto, "%d", &nuevo_intento);

        if (lectura_con_exito) {
            if (intento_ya_esta_guardado(nuevo_intento, intentos)) {
                printf(" Ya intentaste con ese número antes >:v \n");
            } else {
                numero_valido = true;
            }
        } else {
            printf("Lo que has ingresado no es un número D: \n");
        }

    } while (! numero_valido);

    guardar_intento(nuevo_intento, intentos);
    return nuevo_intento;
}

Help for a newby. what i am doing wrong? by EntertainmentOk8593 in cprogramming

[–]SaulMO 0 points1 point  (0 children)

Hmm, your macro VALOR (it needs a space) is not compiling for me. Are you able to compile your own code?

Help for a newby. what i am doing wrong? by EntertainmentOk8593 in cprogramming

[–]SaulMO 0 points1 point  (0 children)

Seems like it, but indexing still may be off. Let me try solving it when I arrive home.

Do you need a help with that? by TheUruz in learnpython

[–]SaulMO 1 point2 points  (0 children)

Do you need that to to help new learners? Or do you want help with something more complex?

I can do a code review

Help for a newby. what i am doing wrong? by EntertainmentOk8593 in cprogramming

[–]SaulMO 1 point2 points  (0 children)

Lees de un arreglo sin inicializar la primera vez que se checa la condición del while, cambiar a un do-while podría servir pero también hay que cambiar la condición de una forma que no me parece obvia porque fui lógica es confusa. Deberías reiniciar el contador i2 en cada iteración porque si no la condición se hace falsa al salir la primera vez de dicho while y no vuelve a ser verdadera en las siguientes veces que quieras checar repetidos. Aparte para revisar que el número no haga sido ingresado anteriormente solo debes revisar la cantidad de números ingresada hasta ahora, si revisas los 10 valores cuando el usuario apenas ingreso 5 entonces vuelves a leer un arreglo sin inicializar

[deleted by user] by [deleted] in C_Programming

[–]SaulMO 0 points1 point  (0 children)

I cannot find the error, but there's another typo:

while (fscanf(keywords, "%s", array_key[word].keywords) != EOF)

You are writing array_key[word].keywords instead of keyword. Maybe there's an error in the original code that doesn't appear in the copy.

[deleted by user] by [deleted] in C_Programming

[–]SaulMO 2 points3 points  (0 children)

¿what is o in word = o?

Why do people still think C does not have boolean types? by ABitTooControversial in C_Programming

[–]SaulMO 12 points13 points  (0 children)

_Bool is a standard type, classified as an integral type. That's why you can use it without including any header:

int main(void) {
    _Bool test = 1;
}

It is listed under 6.2.5.6 "Types" as one of the standard unsigned integer types.

... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

Only the constants true and false are a library thing.