int an bestimmter Stelle auslesen

ProgFreak

Mitglied
Hallo!

Ich habe ein Problem.
Ich muss eine int Variable x mit dem Wert 012345 an einer bestimmten Stelle ausgeben. z.B. ich brauche die 2 Stelle und er soll mir dann 1 zurückliefern. Wie mach ich das?

Vielen Dank

ProgFreak
 
Hallo,

Mit Arithmetik:
C:
#include <math.h>
#include <stdio.h>

int main() {
    int x = 12345;
    int stelle = 2;

    int stellen = (int)floor(log10(x)) + 1;
    if (stelle < 1 || stelle > stellen) {
        printf("Ungültige Stellenangabe!\n");
        return -1;
    }
    int ergebnis = x/(int)pow(10, stellen-stelle) % 10;
    printf("Die %d. Stelle von %d ist %d",
        stelle,
        x,
        ergebnis
    );

    return 0;
}

Mit Strings:
C:
#include <string.h>
#include <stdio.h>

int main() {
    int x = 12345;
    int stelle = 2;

    char szZahl[12];
    sprintf(szZahl, "%d", x);
    int stellen = strlen(szZahl);
    if (stelle < 1 || stelle > stellen) {
        printf("Ungültige Stellenangabe!\n");
        return -1;
    }
    int ergebnis = szZahl[stelle-1] - '0';
    printf("Die %d. Stelle von %d ist %d",
        stelle,
        x,
        ergebnis
    );

    return 0;
}

Grüße,
Matthias
 
Zurück