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.
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 am new to programming so please help me completing the task
the problem is:
After pressing y the while loop does not run again.
and secondly, how to print or get the array elements in descending order?
thank you!
#include <iostream>
using namespace std;
int main()
{
int item;
int flaging = 0;
int ind_low = 0;
int ind_high = 9;
int ind_mid = (ind_low + ind_high) / 2;
char conti;
//Array declaration and taking user input
int arr[10];
cout << "enter some values here : \n" << endl;
for (int i = 0; i < 10; i++)
{
cin >> arr[i];
}
// for sorthing the array
int temp;
for (int p = 1; p <= 9; p++)
for (int c = 0; c <= 8; c++)
if (arr[c] > arr[c + 1])
{
temp = arr[c];
arr[c] = arr[c + 1];
arr[c + 1] = temp;
}
do {
//asking for searching
cout << "Enter the value you want to search : " << endl;
cin >> item;
while (ind_low <= ind_high)
{
if (item == arr[ind_mid])
{
cout << "At " << ind_mid << " index the value " << item << " is found " << endl;
flaging++;
break;
}
if (item < arr[ind_mid])
{
ind_high = ind_mid - 1;
ind_mid = (ind_low + ind_high) / 2;
}
else
{
ind_low = ind_mid + 1;
ind_mid = (ind_low + ind_high) / 2;
}
}
if (flaging == 0)
{
cout << "Value not found" << endl;
}
cout << "To search again press 'y', to exit press any key" << endl;
cin >> conti;
} while ((conti == 'y') || (conti == 'Y'));
}
when I ran it on my pc after pressing y it did run again, can you provide the input that failed you?
for the second question what do you mean?
you can do a for loop that goes like this:
for(int index = ARR_SIZE -1 ; index >= 0 ; --index){
cout << array[index];
}
edit: I understand what you mean. after each run you should reset your indexes otherwise you will always run on the same once:
before you end the loop the values should be reseted.
ind_low = 0;
ind_high = 9;
ind_mid = (ind_low + ind_high) / 2;
that gonna print the array from end to start.
I am trying to make this shape from the code below. I'm confused as to how to make it print the 2nd row, second to last star without it skipping and printing the extra space before printing the star. Once that is figured out would the bottom half, when the stars expands back out, would the code be similar to the top half? I have tried a couple combinations of code between c and r but I have been stuck with what I currently.
---------------------- //row 0
* *| //row 1
* * * *| //row 2
* * * * * *|
* * * * * * * *|
* * * * * * * * * *|
* * * * * * * * * * *|
* * * * * * * * * *|
* * * * * * * *|
* * * * * *|
* * * *|
* *|
----------------------
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
for (int c = 0; c < num; ++c) //inner loop/columns
{
if (r == 0) cout << "--"; //top of square
else if (c >= r + r - c && c < num - 1)
cout << " ";
//else if (c == num - 1) cout << "*|";
else if (r == num - 1) cout << "--"; //bottom of square
else if (c == num - 1) cout << "*|"; //right side of square
else if (r > c) cout << "* ";
}
cout << endl;
}
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
I just took two variables left=0 & right=num-1 and increased left & decreased right till r<=num/2, after that i reversed the process,when the col <= left or col >=right I printed *.
I hope it will be easy to understand.
Here is the code:
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
int left=0,right=num-1;
//for printing top line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
//printing columns
for(int c = 0; c < num; c++)
{
if(c <= left || c >= right)
cout<<"* ";
else
cout<<" ";
}
if(r >= num/2) //checking for half of the rows
{
left--;right++;
}
else
{
left++;right--;
}
cout<<"|"<<endl;
}
//for printing last additional line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
This approach does it the math way.
Furthermore it draws a full frame with plus-chars at the edges.
Give it a try.
#include <iostream>
#include <cmath>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a) {
cin >> num;
if (num < 40 && num > 0 && num % 2 == 1) {
cout << "Thank you!" << endl << endl;
int center = ceil(num / 2.0);
for (int r = 0; r <= num+1; ++r) { //outer loop/rows
for (int c = 0; c <= num+1; ++c) { //inner loop/columns
if (r == 0 || r == num+1) {
if (c == 0 || c == num+1)
cout << "+"; // corner
else
//top or botton of square between corners
if (c == center)
cout << "-";
else
cout << "--";
}
else if (c == 0 || c == num+1) {
cout << "|"; // left or right frame
} else {
// inner part
if ((center-std::abs(center-r)) >= center-std::abs(center-c))
if (c < center)
cout << "* ";
else if (c > center)
cout << " *";
else
cout << "*";
else
if (c == center)
cout << " ";
else
cout << " ";
}
}
cout << endl;
}
} else
cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
Just another way (with some more user input checking):
#include <iostream>
#include <string>
#include <limits>
#include <sstream>
using std::cout;
using std::cin;
using std::string;
const auto ssmax = std::numeric_limits<std::streamsize>::max();
const int max_dim = 40;
const int max_iter = 3;
int main() {
cout << "Enter a positive odd number less than " << max_dim << ": ";
int num = 0, counter = 0;
while ( counter < max_iter ) {
cin >> num;
if ( cin.eof() )
break;
if ( cin.fail() ) {
cout << "Please, enter a number!\n";
cin.clear();
cin.ignore(ssmax,'\n');
}
if ( num < max_dim && num > 0 && num % 2 ) {
cout << "Thank you!\n\n";
//top line
string line(num * 2, '-');
cout << line << '\n';
for ( int r = 0, border = num - 1; r < num; ++r ) {
cout << '*';
for ( int c = 1; c < num; ++c ) {
if ( (c > r && c < border) || (c < r && c > border) )
cout << " ";
else
cout << " *";
}
// right border
cout << "|" << '\n';
--border;
}
//bottom line
cout << line << '\n';
++counter;
} else {
cout << "Please, enter a positive odd number that is less than 40!\n";
}
}
cout << std::endl;
}
Or my favorite:
// top line
string line = string(num * 2, '-') + '\n';
cout << line;
// inside lines
int r = 0, border = ( num - 1 ) * 2;
string inside = string(border + 1, ' ') + "|\n";
// top
while ( r < border ) {
inside[r] = '*';
inside[border] = '*';
r += 2;
border -= 2;
cout << inside;
}
// center line
inside[r] = '*';
cout << inside;
// bottom
while ( border > 0 ) {
inside[r] = ' ';
inside[border] = ' ';
r += 2;
border -= 2;
cout << inside;
}
//bottom line
cout << line;
I am writing a program where the input data (in binary) is split into half and convert to integer to perform some calculation.
So I:
Accept binary input and store as "String"
Split string (note: to be treated as binary) into half and convert to int and store in x and y
So far i have written step 1.
int main() {
string input;
cout << "Enter data:";
getline(cin, input);
int n = input.size();
int n1 = n/2;
string a, b;
a = input.substr(0,n1);
b = input.substr(n1);
cout << "a: " << a;
cout << "b: " << b;
}
Would like to know how to achieve step 2.
Thanks in advance.
You can try this:
if(a.length() <= sizeof(unsigned int) * 8) {
unsigned x = 0;
for(int i = 0; i < a.length(); i++) {
x <<= 1; // shift byt 1 to the right
if(a[i] == '1')
x |= 1; // set the bit
else if(a[i] != '0') {
cout << "Attention: Invalid input: " << a[i] << endl;
break;
}
}
cout << "Result is " << x << endl;
}
else cout << "Input too long for an int" << endl;
It uses
shift left <<, to move the binary bits, when you go right in the ascii string;
binary or | for setting the bits.
int bin2dec(char* str) {
int n = 0;
int size = strlen(str) - 1;
int count = 0;
while ( *str != '\0' ) {
if ( *str == '1' )
n = n + pow(2, size - count );
count++;
str++;
}
return n;
}
int main() {
char* bin_str = "1100100";
cout << bin2dec(bin_str) << endl;
}
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";
}