Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The following code
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool qualities(double number){
//function qualities, irrelevant to question
}
int main(){
double pandigital = 123456789;
double sum = 0;
string strpan = to_string(pandigital);
while (next_permutation(strpan.begin(), strpan.end())){
cout << strpan << endl;
if (qualities(pandigital)){
sum += pandigital;
}
next_permutation(strpan.begin(), strpan.end());
break;
}
cout << "sum is " << sum << endl;
cin.get();
}
has the following problems beginning at this piece of code
double pandigital = 123456789;
double sum = 0;
string strpan = to_string(pandigital);
while (next_permutation(strpan.begin(), strpan.end())){
cout << strpan << endl;
The problem is strpan has an extra zero appended to it, which is an error. If I add a zero to pandigital so we have 1234567890, it will still append an extra zero.
Zero comes from std::to_string converting a double to string: rather than producing "123456789", it makes "123456789.0".
To fix this problem, declare pandigital as int, or add a cast when converting it to a string:
string strpan = to_string((int)pandigital);
With this issue out of the way, you have another fix to make: each iteration of your while loop calls next_permutation twice - once in the header of the loop, and once in the body. You should remove the invocation that you perform in the body of the loop.
Finally, recall that in order to go through all possible permutations the initial call of next_permutation should be made when the range is sorted. It is not a problem for your number, because the digits are arranged in ascending order, but it may become an issue if you start with a different number.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I tried to make a console application in C++ that calculates the area of a circle using the equation:
pi times radius squared.
By the way, I use Visual Studio to make console applications.
These are the steps the program takes:
Output some text, like the title, the equation.
Get input from the user for the radius and store it in a double(float) variable.
Use the equation: pi times radius squared. But replace the radius with the input from the user.
Output the results.
Sometimes, an annoying round off error(truncation) sometimes rounds off the decimals and I am frustrated.
Here is my code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int main() {
double input = NULL;
const double pi = 3.14;
cout << "Enter in your radius: " << input << endl;
cin >> input;
double acc = pi * pow(2, input);
cout << "The area: " << acc << ". Don't forget to add the measurement type! (example: cm, in)" << endl;
}
I used to have a int for the input variable but I changed it to a double(float) variable. Because it is a double(big float), I thought that it would stop the truncation problem. Still the truncation(round off) problem still sometimes occurs.
I wanted it to output a result that is not rounded, and still am getting the round off error
You can use std::setprecision() to force to display a set number of digits, for example:
#include <iomanip>
// ...
double acc = pi * input * input;
int precision = log10(acc) + 7; // 7 = number of decimals + 1
cout << "The area: " << setprecision(precision) << acc << ". Don't forget to add the measurement type! (example: cm, in)" << endl;
Will yield 6 decimal digits.
Ex: for input : 211.123456 will print out
The area: 139959.576934. Don't forget to add the measurement type! (example: cm, in)
Note that the maximum precision for doubles is 19 digits altogether.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Hi there I have attached my code below and it is not working. I want to eliminate all possibles except number or character. Also no upper and lower case problem. But I don't know why it's not working even after I've tried this far. Please any help would be appreciated.
// C++ program to find if a sentence is
// palindrome
//#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
// To check sentence is palindrome or not
bool sentencePalindrome(string sentence)
{
int j = 0;
int l = sentence.length() - 1;
// Compares character until they are equal
while (j < l) {
//removing spaces and special characters
while(j<l&& isalnum(sentence[j])==0)
j++;
while(j<l && isalnum(sentence[l])==0)
l--;
//Checking if not palindrome
if(toupper(sentence[j])!=toupper(sentence[l]))
{
return false;
}
else
{
j++;
l--;
}
}
return true;
}
// Driver program to test sentencePalindrome()
int main()
{
string sentence;
cout << "enter sentence!" << endl;
cin >> sentence;
int result = sentencePalindrome(sentence);
if (result==1)
cout << "Sentence is palindrome.";
else
cout << "Sentence is not palindrome.";
return 0;
}
Your main issue appears to be the way you are reading in you input in your Main function. Using >> in C++ will only read in one word at a time, so you are not working with the full sentence in the function sentencePalindrome().
You should look at using getline() instead to be able to read an entire sentence in as input.
If you use the debugger, it is much easier to spot the problem. I took your code above and set a breakpoint right as the variable l is being declared on line 13 (you can see the orange dot to the left of the code for it).
When you reach that breakpoint when running the code, you can see that the value of sentence = "Test" down at the bottom, even though my input at the command line was Test the sentence.
Once you fix how you get input, you can check the logic of your program and see if it functions correctly. If you are unfamiliar with debugging, putting in a little time to learn GDB now will save you hours of frustration while coding in the future!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Using c++ 14.
I'm prompting the user for a string containing both letters and integers, and trying to "strip" the integers from the string itself via the string.erase() function.
The problem i'm facing is when there are 2 or more sequential numbers, than the function seems to erase the first but delete the latter.
Example:
input: H23ey Th2e3re St01ack O34verflow
output: H3ey There St1ack O4verflow
I can do it another way by using a new string, looping through the existing one and adding only what isalpha or isspace, but it seems messier.
code:
string digalpha {};
cout << "Enter string containing both numbers and letters: ";
getline(cin, digalpha);
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1);
cout << digalpha << endl;
cout << endl;
return 0;
In the first sentence you were writing that you are using C++14.
In "more modern" C++ the usage of algorithm is recommended. So normally you would not use C-Style For loops.
The standard approach that you can find everywhere, is a combination of erase with std::remove_it. You will find this construct in many many examples.
Please consider to use such a solution instead of a for loop.
You can even include the output in an algorithm using std::copy_if.
Please see:
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
std::string test1{ "H23ey Th2e3re St01ack O34verflow" };
std::string test2{ test1 };
// C++ standard solution for erasing stuff from a container
test1.erase(std::remove_if(test1.begin(), test1.end(), ::isdigit), test1.end());
std::cout << test1 << "\n\n";
// All in one alternative
std::copy_if(test2.begin(), test2.end(), std::ostream_iterator<char>(std::cout), [](const char c) { return 0 == std::isdigit(c); });
return 0;
}
If there's two digits next to each other, it skips the second digit. This happens because the index, i, keeps going up, even though everything got shifted over:
for (size_t i {}; i < digalpha.size(); i++)
if (isdigit(digalpha.at(i)))
digalpha.erase(i,1); //Here, i goes up anyway, skipping character after digit
To fix this, we just have to decriment i after erasing a digit:
for (size_t i {}; i < digalpha.size(); i++) {
if (isdigit(digalpha.at(i))) {
digalpha.erase(i,1);
i--;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am learning C++ and I have a problem with my program. It should print out following if n=11:
*---------*
-*-------*-
--*-----*--
---*---*---
----*-*----
-----*-----
----*-*----
---*---*---
--*-----*--
-*-------*-
*---------*
This is my code, which works correctly with n=5, but not with greater numbers:
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter size (n x n): " << endl;
cin >> n;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if (i%n==j%n) cout << '*';
else if (i%(n-i)==j%(n-j)) cout << '*';
else cout << '-';
}
cout << endl;
}
return 0;
}
This is being printed out if n=11:
*---------*
-*----*--*-
--*-----*--
---*---*---
----*------
-----*-----
-*----*--*-
---*---*---
--*-----*--
-*----*--*-
*---------*
I see that I have successfully wrote how to print out one of '*' diagnoles. But something isn't working with other one, which is going backwards.
Unfortunately, I am not being able to resolve this problem and need your advice. What am I doing wrong? How to debug such problems?
This problem is really simple to debug.
Take a look at the first erroneous *. It appears at the position with i=1, j=6. With n=11, your condition i%(n-i)==j%(n-j) becomes 1%(11-1) == 6%(11-6) which is effectively true because the expression evaluates to 1 on both sides.
What is behind this expression? Why do you use this kind of if to determine whether the cell belongs to the second diagonal? Try to write down each pair i, j which should be printed on the second diagonal, and you should notice a more simple pattern.
P.S. In the expression if (i%n==j%n) you don't have to take operands modulo n, because both of them are less than n, so it is redundant and may be rewritten simply as if (i == j).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am writing a code to subtract the adjacent elements of a vector and enter the answer into a new vector. However, my code isn't working. What exactly is wrong with it?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int length;
vector<int>values;
vector<int>values2;
cout << "Enter the length of the vector";
cin >> length;
values[0]=1; values[1]=2; values[2]=3; values[3]=4; values[4]=5;
for(int i=0; i<length; i++)
{
cout<<"Enter the " << i <<"th element of the vector";
cin >> values[i];
}
for (int i=0; i<length-1; i++)
{
values2[i]=values[i+1]-values[0];
}
return 0;
}
You need to size the vectors accordingly before accessing elements. You can do that on construction, or using resize.
vector<int>values(5/*pre-size for 5 elements*/); and similar for values2 would fix your problem.
Currently your program behaviour is undefined.
If you want to subtract adjacent elements, then shouldn't you have values2[i]=values[i+1]-values[i];?
The line of code:
values2[i]=values[i+1]-values[0];
will take the looked-at element away from the first element each time.
Did you mean:
values2[i]=values[i+1]-values[i];
?