I'm trying a lab exercise which wants user to input a 2 4-digit integer. Then the program will extract all the numbers in the 4-digit integer and use the number to do an arithmetic calculation just like the image link below.
Arithmetic Calculation with 2 4-digit integer
However, the objective for this lab exercise is not to allow me myself, to use a for loop to obtain the result.
For instance, when i want to obtain the last number of the 4 digit integer, I could easily do it by using this.
int firstDigit = firstNo % 10; //i will get 4 if the integer is 1234
int secondDigit = secondNo % 10; //i will get 8 if the integer is 5678
And of course table formatting is nothing to worry about before getting the logic right. Next is a very simple calculation of the numbers using the digit i obtain from the above.
int addfirstNumbers = firstDigit + secondDigit;
int minusfirstNumbers = firstDigit - secondDigit;
int multiplefirstNumbers = firstDigit * secondDigit;
int modfirstNumbers = firstDigit % secondDigit;
double divfirstNumbers = firstDigit / secondDigit;
cout << "add: " << addfirstNumbers << endl
<< "minus " << minusfirstNumbers << endl
<< "multipile " << multiplefirstNumbers << endl
<< "remainder " << modfirstNumbers << endl
<< "division " << divfirstNumbers << endl;
I do understand forloop can make my life easier. But i'm just trying out the long method before trying out the shorter way which is forloop.
But even before i proceed, I'm still unable to extract out the other digit from this 4 digit integer.
Like Mike Vine mentioned in the comments, you can do integer division before taking the modulo.
#include <iostream>
int main(){
int x = 1234;
std::cout << (x/10)%10 << "\n";
}
#Output
3
Edit: This works for all places of a number. To find the nth value from the end, just keep adding 0s to the divisor. For example to find the 2nd from the last, you'd want to divide x by 100 instead.
You could simply do
int secondLastDigit = ((i - (i % 10)) % 100)) / 10;
For i=5678:
i % 10 (5678 % 10) equals 8
i - (i % 10) (5678 - 8) therefore equals 5670.
(i - (i % 10)) % 100 (5670 % 100) equals 70
Finally (i - (i % 10)) % 100) / 10 (70 / 10) = 7
This is pretty simple, just use the modulus operator on the number for 100(num%100), getting the last two digits that way, and then divide that result by ten, and store the digit in an int (so the decimal is properly truncated.)
Related
Sorry if this is a dumb question, this is my first coding class.
If the checksum is 10, the last digit is denoted as X according to the
ISBN-10 convention. Write a program that prompts the user to enter the
first 9 digits and displays the 10-digit ISBN (including leading
zeros). Your program should read the input as an integer.
A sample run should look something like this:
Enter the first nine digits of the ISBN: 013601267
The ISBN-10 number is: 0136012671
I have successfully made a program that can do this but using int value for all nine numbers. Unfortunately, this required the user to input every number separately.
So what I am trying to do now is use use a string ISBN so that I can target individual sections ie. isbn[0] * 1 + isbn[1] * 2...
I have also tried static_cast<char>(ISBN[0]) * 1 + static_cast<char>.... thinking it would do something and I get the same results.
string ISBN;
cout << "Enter the first nine digits of the ISBN as integer: ";
cin>>ISBN;
int n10 = (ISBN[0] * 1 + ISBN[1] * 2 + ISBN[2] * 3 + ISBN[3] * 4 + ISBN[4] * 5 + ISBN[5] * 6 + ISBN[6] * 7 + ISBN[7] * 8 + ISBN[8] * 9) % 11;
if (n10 == 10)
{
cout << ISBN << "X" << endl;
}
else
{
cout << ISBN << n10 << endl;
}
So when I input this number 013601267 I should get a 1 (0136012671) at the end instead I am getting a 5 (0136012675).
I think this is happening because it is giving me ASCII dec value instead of the char value.
Four things you should check:
1: The size of the string is actually 9 characters.
if (ISBN.size() != 9) {
// Error
}
Otherwise accessing elements that do not exist will cause an error in your program.
2: The digits do not start at value 0. In ASCII (or UTF-8) the digits start at 48. Therefore 48 => '0' 49 => '1' etc. But C++ guarantees all the digits are contiguous so as long as you know the first one you can subtract that and get a correct value. If you use '0' in an integer expression it will convert to the correct value. Thus to generate a number value from a char you should subtract this value from each digit before multiplying.
n10 = ((ISBN[0] - '0') * 1) + ((ISBN[1] - '0') * 2) + ...
3: But you should check the string is all digits.
for(auto x: ISBN) {
if (!std::is_digit(x)) {
// ERROR
}
}
4: To print a string of 9 characters with leading zero you need to make sure you prep the stream coreectly:
std::cout << std::setw(9) << std::setfill('0') << number;
Or if the number is already in a string form that you know is 9 characters long you can simply use:
std::cout << ISBN;
So To output the correct 10 character number in your case:
std::cout << ISBN << ((n10 == 10) ? 'X' : ('0' + n10)) << "\n";
First you should check the size of string
if(ISBN.size() != 9){
// ERROR
}
You can use for to calculate 'n10'
int n10 = 0;
for(int i = 0; i < ISBN.size(); ++i){
if(std::is_digit(x)){ // check digit
// characters '0','1','2'... are not same as digits 0, 1, 2...
// the value of '0' is 48, as shown here [ascii table][1]
n10 = (ISBN[i] - '0') * (i+1) + n10;
} else {
// ERROR
}
}
My code here finds the sum of some given multiples less than or equal to a certain number. It uses a modified version of a formula I read about on the internet a while ago (the one for finding the sum of all the numbers less than or equal to 100, or 1000 or something- when I wrote my formula while I was waiting to be picked up at the ymca so it might not look like the one from the internet). So for me I used (n+x)(n/x/2), where n is the limit (for example 1000), and x is the multiple you are using (so 1, or 3, or 5). So if n = 1000 and x = 5, it should find the sum of all multiples of 5 less than or equal to 1000).
Sometimes it adds up correctly and sometimes it doesn't.
For example, if I choose 1 and 2 as the multiples, and 20 as the limit, it prints out 320 (which is correct if you add 1+2+3...+20 and then add to that 2+4+6...+20).
But if I do the multiples of 3 and 5 and 1000 as the limit, it prints out 266,998 (which is wrong according to the internet).
I do not understand why it worked in the first instance but not the second (I have only taken 1 year of high school math, I'll be a sophomore).
Here is the code:
/*
Finds the sum of all inputted multiples below a certain number
For example, it could find the sum of all the multiples of 3 and 5 less than
or equal to 1000
Written By Jay Schauer
*/
//Data Declarations
#include <iostream>
int main()
{
using namespace std;
int a; //Stores the number of multiples being used
cout << "Enter the amount of multiples you would like to use (up to 50
<< endl;
cout << "(for example, enter '2' if you would like to use two multiples,
maybe 3 and 5?)" << endl;
cin >> a;
cout << "Next, you will enter the mutliples you want to use." << endl;
cout << "(for example, if you want to find the sum of the multiples of 3
and\n5 below a given amount, enter 3 as 'multiple 1' and 5 as 'multiple
2')" << endl;
int multiples[50]; //Stores the multiples being used
for (int i = 0; i < a; i++)
{
cout << "Enter 'multiple " << (i + 1) << "'" << endl;
cin >> multiples[i];
}
int limit; //Stores the limit
cout << "Enter the the limit for how high you want to add the multiples
<< endl;
cout << "(for example, you could set the limit to 1000 to find the sum
of the\nmultiples of 3 and 5 (if you entered those) less than and or
equal to 1000)" << endl;
cin >> limit;
int sum(0); //Stores the sum
for (int i = 0; i < a; i++)
{
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
}
cout << "The sum is "<< sum << endl;
system("pause");
return 0;
}
EDIT: I believe the problem might lie in the code not in the formula, because using it on multiples of 3 with 21 as the limit causes it to print out 72, not 84 like it should. I am still unsure of the coding error.
EDIT 2: I changed the for loop to this so it hopefully will function when the limit isn't a multiple of the multiple
for (int i = 0; i < a; i++)
{
int max = limit; /*This is done so I can change max in case it isn't
a multiple of the multiple*/
while (max % multiples[i] != 0) max--;
sum += ((max + multiples[i]) * (max / multiples[i] / 2));
}
Change
sum += ((limit + multiples[i]) * (limit / multiples[i] / 2));
to
sum += (limit + multiples[i]) * (limit / multiples[i]) / 2;
As it is, for your example of 3 and 21, you're computing (24 * (7 / 2)) = 24 * 3 = 72 (integer division of 7 by 2 gives 3, and the remainder is lost), but you want to be computing (24 * 7) / 2 = 84.
Im having trouble with the function taylor2 not returning a value if i input anything over 2. If I enter 0-2 it outputs the correct value but anything over 2 and I just get a flashing underscore with no data returned.
void taylor2(double x)
{
double total = 1;
int i = 0;
int count = 1;
double temp = 1;
do
{
{
if (i % 2 == 1)
{
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total += temp;
}
else {
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total -= temp;
}
}
count++;
i++;
} while (fabs(temp) >= .0001);
cout << "The last recoreded temporary value was: "<<temp << endl;
cout << "The computed value for cosine is : "<< total << endl;
cout << "It took " <<count << " values to calculate the value of the function to .0001 places"<< endl;
cout << endl;
}
I suspect that factorial is returning an int. If int is 32 bit (very common), then factorial will overflow once the argument reaches 13 (i = 5 in your case). Signed integer overflow is undefined behaviour in C++.
You could use a std::uint64_t (an unsigned 64 bit integer). This will allow you to evaluate a few larger factorials.
For more reference, see Calculating large factorials in C++
Better still, use a recurrence relation between your Taylor terms.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm new to C++.
So I found this reverse code on the internet. My prof. told me to make a palindrome checker, so I look for the reverse first.
Here is what I made
void main()
{
int num;
int new_num = 0;
int dummy;
cout << "Masukkan angka";
cin >> num;
dummy = num;
cout << dummy << endl;
while (num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
if ( new_num == dummy)
{
cout << "true";
}
else
cout<<"false";
getch();
}
The most confusing part is this
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
I found this on the internet and I don't know how it works.
Can someone explain how this code can reverse the number I input? Like when I input 12345, the output would be 54321. I can't understand.
Its talking the last char of your input by using modulo.
input is: 12345
Cycle 1:
new_num is 0, multiply by 10 give 0.
add modulo or your input 12345 % 10 = 5, new_num is now 5.
divide your input by 10 to remove last digit. input = 1234
Cycle 2,3,4 etc.:
new_num is 5, multiply by 10 gives 50.
add modulo or your input 1234 % 10 = 4, new_num is now 54.
divide your input by 10 to remove last digit. input = 123
I have taken the liberty to modify your source, and provide it in a more readable format
int inputNumber = 123;
int reversedNumber = 0;
cout << "The input number is " << inputNumber << endl;
while (inputNumber > 0) {
reversedNumber = reversedNumber*10 + inputNumber%10;
inputNumber = inputNumber/10;
}
cout << "The reversed number is " << reversedNumber << endl;
First of all, always use meaningful variables.
It will be more helpful while reading your code.
Now on to the explanation,
The modulo operator gives the remainder (not quotient!) of a division,
i.e. 5%2 = 1.
In the while loop,
1) We keep over-writing reversedNumber by changing (increasing) its decimal position (multiply by 10) and adding the remainder of the division of inputNumber and 10
2) We over-write reversedNumber by changing (decreasing) its decimal position (divide by 10).
I encourage you to actually trace out the program on paper, or printing the variable's values (debugging?) to see how this operation works.
First take a look at what num % 10 does:
#include <iostream>
int main() {
for (int i = 0; i < 100; ++i) {
std::cout << i << " % 10 = " << i % 10 << '\n';
}
}
http://coliru.stacked-crooked.com/a/8d26b893682b0001
Do you see the pattern? This expression basically just gets the least significant decimal digit from a number.
You should know the pattern in new_num*10 without even looking, since we learned this in elementary school math: It shifts the digits to the left one place.
Then if you think about what addition will do in this case, new_num*10 + num % 10, you should see that adding a number in the range [0..9] to an integer where the lowest digit is zero, will just replace that zero with the new digit.
num/10 shifts digits to the right, and since it's using integral division the fractional parts are discarded.
So all together we have:
int remove_last_digit(int value) { return value / 10; }
int get_last_digit(int value) { return value % 10; }
int push_digit(int value, int digit) {
return value * 10 + digit;
}
bool has_more_digits(int value) { return value != 0; }
int reverse_int(int value) {
int reversed_value = 0;
while ( has_more_digits(value)) {
reversed_value = push_digit(reversed_value, get_last_digit(value));
value = remove_last_digit(value);
}
return reversed_value;
}
Think of a number as digits piled on top of each other. If you take the top digit and put it on top of a second pile, and keep doing that until the first pile is empty, then the digits in the second pile are now stacked in the reverse order.
So I am trying to encrypt a four digit integer by adding seven to the digit then dividing the whole digit by ten. In my program I am taking each single digit separately and then I need to divide the whole digit by ten. How can I combine all the separate int into one four digit number?
#include "stdafx.h"
using namespace std;
int main()
{
//Define all variables needed
int a,b,c,d,enc,ext;
//Print dialog and input each single digit for the four number digit
cout << "Enter Your First Digit:" << endl;
cin >> a;
cout << "Enter Your Second Digit:" << endl;
cin >> b;
cout << "Enter Your Third Digit:" << endl;
cin >> c;
cout << "Enter Your Fourth Digit:" << endl;
cin >> d;
//Add seven to each digit
a += 7;
b += 7;
c += 7;
d += 7;
a /= 10;
b /= 10;
c /= 10;
d /= 10;
cout << "Your encrpyted digits:" << c << d << a << b <<endl;
cout << "Enter 1 to exit:" <<endl;
cin >> ext;
if (ext = 1) {
exit(EXIT_SUCCESS);
}
}
As you probably noticed I am dividing each number separately. I need to do them together. Then I am also creating a decrypting which I will get me back to the original number in a separate program.
Based on your comment you are trying to do a variation on the Caesar Cipher, in which case you should be using the modulus operator (%) not the integer division operator (/). Using integer division loses information which will prevent you from decrypting. When your digit is in {0, 1, 2} your division results in a 0. When it is in {3, 4, 5, 6, 7, 8, 9}, the division results in a 1. You can't decrypt {0, 1} back into the original number without some additional information (which you have discarded).
If you want to encrypt on a digit by digit basis using the Caesar Cipher approach, you should be using modulo arithmetic so that each digit has a unique encrypted value which can be retrieved during decryption. If that's really what you are looking for then you should be doing something like the following to encrypt with a 7:
a = (a + 7) % 10;
b = (b + 7) % 10;
c = (c + 7) % 10;
d = (d + 7) % 10;
To decrpyt, you subtract 7, which in mod 10 arithmetic is an addition by 3, so that would be:
a = (a + 3) % 10;
b = (b + 3) % 10;
c = (c + 3) % 10;
d = (d + 3) % 10;
This of course presupposes you've properly validated your input (which isn't the case in your example above).
Combining the individual digits into one four-digit number is simple; just multiple the first digit by 1000, add the second multiplied by 100, and so on.
But this is a one-way algorithm; you will never be able to retrieve the original four-digit number from this.
This is what youd'd probably be looking for :
int e = (a*1000)+(b*100)+(c*10)+d;
e=e/10;
It's not clear from your description whether the addition should be modulo 10 or not; if so
((((((a % 10) * 10) + (b % 10)) * 10) + (c % 10)) * 10) + (d % 10)
if you don't want the modulo 10
(((((a * 10) + b) * 10) + c) * 10) + d
Stepping aside the fact that you almost certainly want mod instead of divide (as #Andand has said), there's more than one way to turn the digits into a number!
A lot of people using interpreted languages these days would probably want to do it symbolically. C++ can do that too, fairly neatly in fact:
// create a string stream that you can write to, just like
// writing to cout, except the results will be stored
// in a string
stringstream ss (stringstream::in | stringstream::out);
// write the digits to the string stream
ss << a << b << c << d;
cout << "The value stored as a string is " << ss.str() << endl;
// you can also read from a string stream like you're reading
// from cin. in this case we are reading the integer value
// that we just symbolically stored as a character string
int value;
ss >> value;
cout << "The value stored as an integer is " << value << endl;
It won't be as efficient as multiplications in this narrow case of a 4 digit number, because of the round trip to a string and back. But good to know the technique. Also it's a style of coding that can be a lot easier to maintain and adapt.
You'll get stringstream if you #include <sstream>.