Given the C code below:
int nSum = 0;
// pNumber is 9109190866037
int nDigits = strlen(pNumber);
int nParity = (nDigits-1) % 2;
char cDigit[2] = "\0";
for (int i = nDigits; i > 0 ; i--)
{
cDigit[0] = pNumber[i-1];
int nDigit = atoi(cDigit);
if (nParity == i % 2) {
nDigit = nDigit * 2;
}
nSum += nDigit/10;
nSum += nDigit%10;
printf("NUMBER: %d\n", nSum);
}
Outputs:
NUMBER: 13
NUMBER: 13
NUMBER: 16
NUMBER: 22
NUMBER: 29
NUMBER: 29
NUMBER: 38
NUMBER: 39
NUMBER: 48
NUMBER: 48
NUMBER: 50
NUMBER: 59
NUMBER: 59
And this JavaScript code (written in TypeScript, so there actually is typing involved here as well, but it is mostly inferred):
let nSum = 0;
let nDigits = partialIdNumber.length;
let nParity = (nDigits - 1) % 2;
let cDigit = "\0";
for (let i = nDigits; i > 0; i--) {
cDigit = partialIdNumber[i - 1];
let nDigit = parseInt(cDigit);
if (nParity == i % 2) {
nDigit = nDigit * 2;
}
nSum += nDigit / 10;
nSum += nDigit % 10;
console.log("NUMBER: %d", nSum);
}
Outputs:
NUMBER: 14.3
NUMBER: 14.3
NUMBER: 17.5
NUMBER: 24.1
NUMBER: 31.700000000000003
NUMBER: 31.700000000000003
NUMBER: 41.5
NUMBER: 42.6
NUMBER: 52.4
NUMBER: 52.4
NUMBER: 54.6
NUMBER: 64.5
NOTE: Both these implementations are the same, just different languages.
The C code produces the expected results and JavaScript doesn't.
Questions
JavaScript is interpreted and sometimes compiled at runtime with a just-in-time (JIT) compiler. C is statically typed. JavaScript is dynamically typed. C requires programmers to allocate and reclaim blocks of memory.
JavaScript is a cross-platform language, whereas Java is not. Prior to execution on the client, Java needs to be compiled on the server whereas JavaScript is interpreted by the client end. JavaScript is a dynamic language and Java is a static language. JavaScript aims on creating interactive web pages.
If you want to start a simple web application, then learning Javascript instead of C is a fine approach. If you want to learn to write a desktop app, then Javascript is absolutely the wrong way to go about this.
More than that, as a high-level language, JavaScript is easier to type, but more work for the interpreter at runtime. So while you can type up a program in JavaScript much quicker than C++, JavaScript code runs much slower.
You need to convert numbers after using division to an integer value.
var partialIdNumber ='9109190866037'
let nSum = 0;
let nDigits = partialIdNumber.length;
let nParity = (nDigits - 1) % 2;
let cDigit = "\0";
for (let i = nDigits; i > 0; i--) {
cDigit = partialIdNumber[i - 1];
let nDigit = +cDigit;
if (nParity == i % 2) {
nDigit = nDigit * 2;
}
nSum += Math.floor(nDigit / 10); // int
nSum += nDigit % 10;
console.log("NUMEBR: %d", nSum);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With