Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
tenho um código em C++ e gostaria de fazer ele idêntico para Javascript mas não tenho conhecimento pra isso, alguem pode me ajudar?? Segue o código abaixo em C++:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * unidades[] = { "Zero", "Um", "Dois", "Tres", "Quatro", "Cinco", "Seis", "Sete", "Oito", "Nove" };
char * dez_vinte[] = { "", "Onze", "Doze", "Treze", "Quatorze", "Quinze", "Dezesseis", "Dezessete", "Dezoito", "Dezenove" };
char * dezenas[] = { "", "Dez", "Vinte", "Trinta", "Quarenta", "Cinquenta", "Sessenta", "Setenta", "Oitenta", "Noventa" };
char * centenas[] = { "", "Cento", "Duzentos", "Trezentos", "Quatrocentos", "Quinhentos", "Seiscentos", "Setecentos", "Oitocentos", "Novecentos" };
char * strcatb( char * dst, const char * src )
{
size_t len = strlen(src);
memmove( dst + len, dst, strlen(dst) + 1 );
memcpy( dst, src, len );
return dst;
}
char * traduzir_numero( char * nome, int n )
{
int c = n / 100;
int d = n / 10 - c * 10;
int u = n - (n / 10) * 10;
int dv = d * 10 + u;
strcpy( nome, unidades[ u ] );
if( n < 10 )
return nome;
if ( (dv > 10) && (dv < 20) )
{
strcpy( nome, dez_vinte[ dv - 10 ] );
}
else
{
if( u == 0 )
{
strcpy( nome, dezenas[ d ] );
}
else
{
strcatb( nome, " e " );
strcatb( nome, dezenas[d] );
}
}
if( n < 100 )
return nome;
if( (d == 0) && ( u == 0 ) )
{
if( c == 1 )
strcpy( nome, "Cem" );
else
strcpy( nome, centenas[c] );
}
else
{
strcatb( nome, " e " );
strcatb( nome, centenas[c] );
}
return nome;
}
int main( int argc, char * argv[] )
{
int i = 0;
char extenso[ 100 ] = {0};
int num[] = { 0, 1, 10, 13, 100, 123, 321, 111, 333, 777, 910, -1 };
while( num* != -1 )*
*
{*
*
traduzir_numero( extenso, num** );
*
*
**
printf( "%d: %s\n", num**, extenso );
*
*
**
i++;*
*
}
*
*
**
return 0;*
*
*
*
printf("\n\nFim...");*
*
*
*
getchar();*
*
*
*
}
*
*
**
*
e como faço para rodar este código no HTML?
Desculpe minha ignorância, mas estou começando a estudar agora e meu professor já pediu que desenvolvesse um código em HTML e Javascript onde o usuário digite um numero qualquer e o JS retorna o valor por extenso.
>
11 horas atrás, leosbotelho disse:
ES6+, minha versão:
const numToNamesDict = {
'pt-BR': new Map(Object.entries({
'groups': [
[
'um', 'dois', 'tres', 'quatro', 'cinco', 'seis',
'sete', 'oito', 'nove'
],
[
'dez', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta',
'setenta', 'oitenta', 'noventa'
],
[
'cento', 'duzentos', 'trezentos', 'quatrocentos', 'quinhentos',
'seiscentos', 'setecentos', 'oitocentos', 'novecentos'
],
],
'large-groups': [
['', ''],
['mil', 'mil'],
['milhao', 'milhoes'],
['bilhao', 'bilhoes'],
['trilhao', 'trilhoes']
],
'group-sep': ' e ',
'large-group-inner-sep': ' ',
'large-group-outer-sep': ', ',
'large-group-outer-sep-distinct': ' e ',
'fixed': new Map([
[0, 'zero'],
[100, 'cem']
]),
'fixed-pieces': new Map([
[11, 'onze'],
[12, 'doze'],
[13, 'treze'],
[14, 'quatorze'],
[15, 'quinze'],
[16, 'dezesseis'],
[17, 'dezessete'],
[18, 'dezoito'],
[19, 'dezenove']
]),
'positive': '',
'negative': ' negativo'
}))
};
const flatten = xss => [].concat.apply([], xss);
const _throw = x => {throw x};
const _validate = (x, y) =>
!(Number.isInteger(x) && Number.isInteger(y) &&
!(x === 1 && y === 1) && y > 0 && x >= 0) &&
_throw(new Error(`Invalid nums supplied: ${x}, ${y}`));
const divMod = (x, y) => [Math.trunc(x/y), x%y];
function* _splitNum(x, y) {
const [d, m] = divMod(x, y);
if(d === 0) {
yield x;
} else {
yield m;
yield* _splitNum(d, y);
}
}
function* splitNum(x, y) {
_validate(x, y);
yield* _splitNum(x, y);
}
const groupToName = dict => y => n => {
_validate(n, y);
const groups = dict.get('groups');
const fixed = dict.get('fixed');
const fixedPieces = dict.get('fixed-pieces');
if(fixed.has(n)) {
return fixed.get(n);
}
const f = (i, y, n) => {
const y1 = Math.trunc(y/10);
const [d, m] = divMod(n, y1);
return (d === 0 ? [] :
d <= groups[i-1].length ? [groups[i-1][d-1]] :
_throw(new RangeError(
`The digit ${d} is not defined in the ${i}-th group`
))
).concat(
fixedPieces.has(m) ?
fixedPieces.get(m) : (m !== 0 ? f(i-1, y1, m) : [])
);
};
return (n < y) ?
f(groups.length, y, n).join(dict.get('group-sep')) :
_throw(new RangeError(
`Groups must have at most ${groups.length} digits, ` +
`${n} supplied.`
));
};
const numToNameIntermediate = dict => y => n => {
const largeGroups = dict.get('large-groups');
const groupToName_ = groupToName(dict)(y);
const xs = Array.from(splitNum(n, y));
return (xs.length <= largeGroups.length) ?
xs.reduce((r, x, i) =>
r.concat([
[x, groupToName_(x), largeGroups[i]]
])
, []).reverse() :
_throw(new RangeError(
`The ${xs.length} large-group is not defined.`
));
};
const _numToName = dict => y => n => {
if(n === 0) {
return ['', dict.get('fixed').get(0), '', ''];
}
const innerSep = dict.get('large-group-inner-sep');
const outerSep = [
dict.get('large-group-outer-sep'),
dict.get('large-group-outer-sep-distinct')
];
const y1 = Math.trunc(y/10);
return numToNameIntermediate(dict)(y)(n).map(z => {
const v = z[0];
const m = v%y1;
return v === 0 ? ['', ''] : [
outerSep[(m === 0 || v < y1) ? 1 : 0],
z[1], innerSep,
z[2][(m > 1) ? 1 : 0]
];
});
};
const numToName = dict => y => n =>
flatten(_numToName(dict)(y)(Math.abs(n))).slice(1, -2).join('').concat(
(n >= 0) ? dict.get('positive') : dict.get('negative')
);
const numToNameFn = {
'pt-BR': numToName(numToNamesDict['pt-BR'])(1000)
};
const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1);
//B combinator
const B = f => g => x => f(g(x));
//showcase
const f = B(capitalize)(numToNameFn['pt-BR']);
const print = console.log;
const nums = [0, 1, 10, 13, 100, 123, 321, 111, 333, 777, 910, -1];
nums.forEach(B(print)(f));e como faço para rodar este código no HTML?
Desculpe minha ignorância, mas estou começando a estudar agora e meu professor já pediu que desenvolvesse um código em HTML e Javascript onde o usuário digite um numero qualquer e o JS retorna o valor por extenso.
//showcase
const f = B(capitalize)(numToNameFn['pt-BR']);
const print = window.alert;
const num = Number(prompt('Digite um numero: '));
try {
print(f(num));
} catch(e) {
print(e.message);
}Fix:
110,112c110
< const c = Math.ceil(Math.log10(n)/Math.log10(y));
<
< return (c < groups.length) ?
---
return (n < y) ?
${c+1} digits group supplied.${n} supplied.
));
ES6+, minha versão:
function* _splitNum(x, y) {
function* splitNum(x, y) {
//B combinator
//showcase
/**
* Ouputs:
Zero
Um
Dez
Treze
Cem
Cento e vinte e tres
Trezentos e vinte e um
Cento e onze
Trezentos e trinta e tres
Setecentos e setenta e sete
Novecentos e dez
Um negativo
**/