I'm having difficulty printing a reversed number. The algorithm is working as expected for the reversal of the user's input but cannot display correctly:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int rem, OriValue, InValue2 = 0, InValue = 0;//rem = remainder,InValue = User input
bool neg = false; // Boolean Variable to remember input value
//Request customer to enter a int value
cout << "Enter any decimal integer value >= 0:";
cin >> InValue;
OriValue = InValue;
if(InValue < 0)
{
neg = true;
InValue = -InValue;
cout << "Input value is negative :" << InValue <<"\n";
}
else if (InValue > 0 )
cout << "Input value is positive:"<< InValue <<"\n";
do
{
rem = (InValue % 10);
cout << "Remainder value:"<< rem << "\n";
InValue = InValue / 10;
}
while (InValue != 0);
cout << OriValue << " in reverse is " << InValue << "\n";
// Here is an example of the output:
// -123 in reverse 321
return 0;
}
How can I resolve the problem?
This shoule do the work. Check the comments in the code
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int rem, OriValue, InValue2 = 0, InValue = 0;//rem = remainder,InValue = User input
int reverseVal = 0; // Add this variable to store the reverse number
bool neg = false; // Boolean Variable to remember input value
//Request customer to enter a int value
cout << "Enter any decimal integer value >= 0:";
cin >> InValue;
OriValue = InValue;
if(InValue < 0)
{
neg = true;
InValue = -InValue;
cout << "Input value is negative :" << InValue <<"\n";
}
else if (InValue > 0 )
cout << "Input value is positive:"<< InValue <<"\n";
do
{
rem = (InValue % 10);
cout << "Remainder value:"<< rem << "\n";
InValue = InValue / 10;
// Add this to store
reverseVal = reverseVal*10 + rem;
}
while (InValue != 0);
cout << OriValue << " in reverse is " << reverseVal << "\n";
// Here is an example of the output:
// -123 in reverse 321
return 0;
}
You haven't stored your reversed variable anywhere, and n == 0 is when your loop terminates. When you print n after your loop ends, it has to be 0 as you're seeing. The solution is to store your remainders as you divide down n.
Here are a couple options for achieving this.
Using stringstream:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int original_value, n;
stringstream ss;
cout << "Enter an integer >= 0:";
cin >> original_value;
n = original_value;
if (n < 0) {
n = -n;
ss << '-';
}
while (n > 0) {
ss << n % 10;
n /= 10;
}
cout << original_value << " in reverse is " << ss.str() << "\n";
return 0;
}
Using reverse:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n = -1234;
string rev = to_string(n);
reverse(rev.begin() + (rev[0] == '-' ? 1 : 0), rev.end());
cout << rev << "\n";
return 0;
}
Sample run:
Enter an integer >= 0: -1234
-1234 in reverse is -4321
If you need an integer at the end, you can always parse it from the string using atoi, istringstream or stoi.
Related
I want to check what the variable "num" is from 0 - 15 How can I check if it is one of those numbers and what number it is so far I've got.
#include <iostream>
using namespace std;
int num = 0;
int main()
{
cout << "Number to check:";
cin >> num;
{
if num = 0;
cout << "0000";
{
if num = 2;
cout << "0010";
{
if num = 1;
cout << "0001";
{
if num = 3;
cout << "0011";
{
if num = 4;
cout << "0100";
{
if num = 7;
cout << "0111";
{
if num = 5;
cout << "0101";
{
if num = 6;
cout << "0110";
{
if num = 8;
cout << "1000";
{
if num = 9;
cout << "1001";
{
if num = 10;
cout << "1010";
{
if num = 11;
cout << "1011";
{
if num = 12;
cout << "1100";
{
if num = 13;
cout << "1101";
{
if num = 14;
cout << "1110";
{
if num = 15;
cout << "1111";
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return 0;
How may I be able to do this If I can't, how can I convert a number to a 4-bit Binary byte? And if possible how can I make sure the number inputted is in the range of 0 - 15 and that there isn't letters in the inputted string
The program below does what you want.
#include<iostream>
#include <bitset>
int main() {
int num = 0;
std::cout << "Number to check: ";
std::cin >> num;
while (std::cin.fail() || num > 15 || num < 0) {
std::cout << "Error! Invalid Input \n";
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << "Number to check: ";
std::cin >> num;
}
std::bitset<4> value;
value = { static_cast<unsigned long>(num) };
std::cout << value.to_string() << "\n";
return 0;
}
Use <bitset>
#include <bitset>
#include <iostream>
#include <string>
int main()
{
std::string input{ "12" };
// std::cin >> input;
unsigned long number = std::stoul(input); // does number checking
if (number < 16) // do value checking
{
std::bitset<4> value{ number };
std::cout << value.to_string() << std::endl;
}
}
Since you declared num as an integer, your program won't work if you input nondigit characters during cin. I believe the shortest variant of your code without dealing with std::bitset would be
const int MAX_BITS = 4;
cout << "Number to check:";
cin >> num;
if (num < 0 || num > (1 << MAX_BITS) - 1) {
cout << "Invalid number, next time enter between 0 and " << (1 << MAX_BITS) - 1;
return 0;
}
for(int bit = MAX_BITS - 1; bit >= 0; --bit){
cout << ((num & (1 << bit)) > 0);
}
cout << endl;
I have something which outputs all the factors for an integer using a fixed loop.
in this case, int_end_int_ = 4
and middle_x_coefficient = 4
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0) // This gets the factors
{
//here
}
}
i have that inside the if loop that if i * 2 == 4, print a string. So i thought that when i = 2, it will output the string.
//inside if loop
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i; //ignore
cout << "prerooted";
preroot2 = i; //ignore
}
It does not output "prerooted", and i have no clue why.
Full Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Quadratic Equation Solver ( to roots )" << endl;
cout << "Enter quadratic equation, e.x (x^2 + 4x + 4) must be in this form" << endl;
string equation;
cout << ">> ";
getline(cin, equation);
if (equation.length() < 12)
{
cout << "Please enter valid string." << endl;
while (equation.length() < 12)
{
cout << ">> ";
getline(cin, equation);
}
}
char middle_x_coefficient = equation[6]; // getting x^2 + 4(this<-)x + 4
char end_int_ = equation[11]; // getting x^2 + 4x + 4 <-- this
int preroot1 = 0;
int preroot2 = 0;
int int_end_int_ = static_cast<int>(end_int_); //convert char to int using static cast for like no reason
//nvm <- https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx this says it is better bc compiler bad or smthn
int_end_int_ -= 48; //This converts the ascii value (52 for 4) to 4 (-48)
int pasti = 0;
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0)
{
cout << i << "this<- i" << endl;
cout << middle_x_coefficient << "this<- x" << endl;
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i;
cout << "prerooted";
preroot2 = i;
}
else if (i + pasti == middle_x_coefficient) {
preroot1 = i;
preroot2 = pasti;
}
pasti = i;
}
}
cout << preroot1 << " " << preroot2 << endl;
return 0;
}
You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.
Instead of using magic number 48, using character literal '0' is better.
Problem is with the if statment inside the while loop. It is not printing the desired output. The else if statement and the else statement seem to work fine
Any help is appreciated
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
while (sum < input) {
// This is the if statement giving me problems
if (input == 1) {
exponent += 1;
sum = 3;
}
// This else if statement seems to work fine
else if (input == 3) {
exponent += 2;
sum = 9;
}
else {
exponent++;
sum *= base;
}
}
// Print output
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
Your logic is wrong (and I have to say a bit bizarre).
If the input is 1 then while (sum < input) is not true and so you never reach your if (input == 1) statement.
REALIZED my mistake. i just moved the if and else if statement to outside the loop
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
if (input == 1) {
exponent += 1;
sum = 3;
}
else if (input == 3) {
exponent += 2;
sum = 9;
}
while (sum < input) {
exponent++;
sum *= base;
}
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
If I understood the objective right from the comments, if conditions are not required. Just replace the condition and simplify the while loop as follows:
while (sum <= input) {
exponent++;
sum *= base;
}
Write a C++ program that asks the user for an integer. The program
finds and displays the first power of 3 larger than the input number
using while
You should probably calculate the answer instead of looping.
#include <iostream>
#include <cmath>
int main() {
int input;
std::cout << "input: ";
std::cin >> input;
int x = 0;
/*
3^x == input
ln(3^x) == ln(input)
x*ln(3) == ln(input)
x == ln(input)/ln(3)
*/
// calculate x = ln(input)/ln(3), round down and add 1
if(input > 0) x = std::floor(std::log(input) / std::log(3.)) + 1.;
std::cout << "answer: 3^" << x << " == " << std::pow(3, x) << "\n";
}
Using C++. My code asks the user for a string input, prints that string back to them in binary, prompts them to enter some binary, and then converts that binary back to a string. When testing the code I enter a string like "bed" and reenter the binary in returns me. When it converts the binary back I will end up with "bbb" so its returning the first 8 bits * the segments of 8.
Any suggestions on fixing this? It seems like my a variable is starting back to 0. I've tried for( int a = z;.....) and this just prints the first 8 bits only( "bed" -> binary -> "b")
My code is:
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
using namespace std;
int main()
{
string stuff;
cout << "type some stuff :" << endl;
getline(cin, stuff);
int convert = 0,
toconvert = 0;
for(int i = 0; i < stuff.length(); i++)
{
cout << bitset<8>(stuff.at(i));
}
string retype;
cout << "type in some sweet binary:" << endl;
getline(cin, retype);
char mycharacter;
for(int z = 0; z < retype.length(); z += 8 )
{
for(int a = 0; a < retype.length(); a++)
{
if (retype.at(a) == '1' )
{
convert = (int)pow( 2,( 7- a));
toconvert = toconvert + convert;
}
else if (retype.at(a) == '0')
{
toconvert = toconvert + 0;
}
else
{
cout << "you did not type binary, try again" << endl;
}
}
mycharacter = char(toconvert);
cout << mycharacter;
toconvert = 0;
}
cout << " " << endl;
return 0;
}
Ok I have been struggling with this code and I think I have it written out right but here is the rules from my teacher
1 = implies right Number, Right Place.
2 = implies right Number, Wrong Place.
0 = implies Wrong Number.
So the computer decides on 12345; the user guesses 11235; the computer should respond with 10221. Hint: Watch out for a double number like 11 when there is only one.
I have it where it does all of that except I can not get it to show a 0 when it is wrong can you please help me every single part is written except that part here is my code
// Programming 2
// Mastermind
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
struct fields{//the list of variables used in my program
int size = 5;;
int range = 9;
char lowest = '0';
string guess;
string answer;
int number;
int correct;
int position;
bool gameover = false;
};
void gameplay(fields & info);//declaring the function
int main()
{
fields game;
gameplay(game);//calling the function
system("pause");
return 0;
}
void gameplay(fields & info){//calling the structure into the function
srand(time(0));//to randomize number
info.answer = "";//getting the number
for (int i = 0; i < info.size; i++)
{
char ch = info.lowest + rand() % info.range;
info.answer += ch;
}
info.number = 1;
info.correct = 0;
info.position = 0;
while (!info.gameover)//using a while loop to let them go until they guess it
{
cout << "Guess #" << info.number << ": Enter 5 numbers that are '0' through '9': ";//asking them to guess
cout << info.answer;
cout << "\n";
cin >> info.guess;
if (info.guess == info.answer)//if the guess is right this will end the game
{
cout << "Right! It took you " << info.number << " move";
if (info.number != 1) cout << "s";
cout << "." << endl;
info.gameover = true;
}
int correctNumbers = 0;
for (char const &ch : info.guess) //seeing if there are numebrs in the guess that is in the answer
{
if (info.answer.find(ch) != string::npos)
{
++correctNumbers;
}
}
int const digits = 5;
int correctPositions = 0;
int correctPosition[digits];
int test = 0;
for (int i = 0; i < digits; ++i)//telling which numbers is correct and displaying the 2 or 0 for number is correct or number is wrong
{
if (info.answer[i] == info.guess[i])
{
++correctPositions;
}
if (info.answer[i] == info.guess[i]){
correctPosition[i] = 2;
cout << correctPosition[i];
}
if (correctPosition[i] != 2){
correctPosition[i] = 1;
cout << correctPosition[i];
}
if (correctPosition[i] != 2 && correctPosition[i] != 1)){
correctPosition[i] = 0;
cout << correctPosition[i];
}
}
cout << "\nYou have " << correctPositions << " numbers in the correct position " <<endl;
cout << "You have " << correctNumbers <<" correct numbers in the wrong position"<< endl;
}
cout << "GAME OVER\n\n";
}