Untitled
unknown
c_cpp
9 months ago
1.8 kB
5
Indexable
/*
Scrivere un sottoprogramma che riceve in ingresso una stringa che rappresenta un’espressione composta da somme e sottrazioni di valori in base
8. La stringa è quindi composta da una serie di sequenze, ciascuna contenente i soli caratteri da ’0’ a ’7’ e rappresentante un valore in base
8; le varie sequenze sono separate da un singolo carattere ’+’ o ’-’ (si assuma che la stringa sia ben formata in base alla descrizione data). Il
sottoprogramma calcola e restituisce il risultato dell’espressione rappresentata nella stringa restituendolo in base 10 come numero intero.
Esempio:
Ingresso: "10-24+3"
Uscita: -9 (cioè il risultato del calcolo in decimale: 8 - 20 + 3)
"10" in base 8 = 1*8^1 + 0*8^0 = 8+0 = 8
"24" in base 8 = 2*8^1 + 4*8^0 = 16+4 = 20
"3" in base 8 = 3*8^0 = 3
8 - 20 + 3 = -9 in base 10
"7+17"
7 in base 8 --> 7
17 in base 8 1*8^1 + 7*8^0 = 8 + 7 = 15
7+15 = 22 in base 10
*/
#include <stdio.h>
#include <string.h>
int calcolaEspressione(char *stringa)
{
int risultato = 0;
int numCorrente = 0;
char operatore = '+';
int len = strlen(stringa);
for(int i = 0; i <= len; i++)
{
if(stringa[i] >= '0' && stringa[i] <= '7')
{
numCorrente = numCorrente * 8 + (stringa[i] - '0');
}
if(stringa[i] == '+' || stringa[i] == '-' || stringa[i] == '\0')
{
if(operatore == '+')
{
risultato += numCorrente;
}
else
{
risultato -= numCorrente;
}
if(stringa[i] != '\0')
{
operatore = stringa[i];
}
numCorrente = 0;
}
}
return risultato;
}
int main() {
// Write C code here
printf("Try programiz.pro");
return 0;
}
Editor is loading...
Leave a Comment