- #1
peterjaybee
- 62
- 0
Hi,
I am having an issue with multiplication in C++. I am writing a program to check the validity of an NHS number. To do this I must;
multiply digit 1 of the NHS number by 10,
multiply digit 2 of the NHS number by 9,
multiply digit 3 of the NHS number by 8 ...etc
The answer from each multiplication is added together to form a total I have called sum.
When I wrote the code, the sum at the end of the process was far too big, so I have written some checks into the program to see at which step the program is going wrong and the only step that seems incorrect is the multiplication itself. This is a bit of a mystery to me.
I have been using different 10 digit numbers as tests. so for example imputing the nhs_number = 1234567890.
I am having an issue with multiplication in C++. I am writing a program to check the validity of an NHS number. To do this I must;
multiply digit 1 of the NHS number by 10,
multiply digit 2 of the NHS number by 9,
multiply digit 3 of the NHS number by 8 ...etc
The answer from each multiplication is added together to form a total I have called sum.
When I wrote the code, the sum at the end of the process was far too big, so I have written some checks into the program to see at which step the program is going wrong and the only step that seems incorrect is the multiplication itself. This is a bit of a mystery to me.
Code:
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
string nhs_number;
cout << "Please enter your 10 digit NHS number and press ENTER: " << endl;
getline(cin, nhs_number);
while (nhs_number.size() != 10 && nhs_number.size() != 0)
{
cout << "The format you have entered is incorrect" <<endl;
cout << "Please re-enter the number" << endl;
getline(cin, nhs_number);
}
if (nhs_number.size() == 0) //breaks the program
return 0;
else {
cout << "The NHS number you have entered is: " << nhs_number << endl;
int i, n, sum;
i = 0;
n = 10;
sum = 0;
// need to set up a for loop to take the ith digit of the NHS number and
// multiply it by a weighing factor.
// The weighing factor (n) is different for each digit
// for digit 0, n=10
// for digit 1, n=9
// for digit 2, n=8 etc
// The final digit (digit 9) is a check digit and is not needed in this
// part of the program.
for (i=0; i<9; i++)
{
// print to screen values as a check of where the program is going wrong
cout << "Current running total is " << sum << endl;
cout <<"NHS number element " << i << " is " << nhs_number[i] << endl;
cout <<"Weighing factor is " << n << endl;
// the next line is where the program goes wrong
cout << "Nhs number digit " << i << " x the weighing factor is "<< (nhs_number[i] * n) << endl;
sum += (nhs_number[i] * n);
n--;
}
cout << sum << endl;
cout << 11 - (sum % 11);
}
return 0;
}
I have been using different 10 digit numbers as tests. so for example imputing the nhs_number = 1234567890.