I'm trying to write a program that would print all palindrome in range [a, b]. I've written this so far, but nothing is printed after I input the values for a, b. What is missing?
#include "stdafx.h"
#include <iostream>
using namespace std;
int t = 0, rmd, z, a, b;
int reverse() {
while (z != 0) {
rmd = z% 10;
t = t * 10 + rmd;
z/= 10;
}
return t;
}
int palin() {
if (a == reverse()) {
return 1;
}
else
return 0;
}
int main() {
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
while (a <= b) {
z = a;
if (palin())
cout << a << endl;
a++;
}
system("pause");
return 0;
}
The problem is that the variable t is not local to your reverse() function. Its value survives to the following invocation, so the result of reverse becomes junk unrelated to the actual call.
You need to make t local to reverse() in order to fix this problem.
In general, it is a good idea to develop a habit of declaring your variables in the innermost scope to which they could belong without breaking your code. In this case, this would be the scope of reverse() function for t, and the scope of main for the remaining variables; palin should take a as its parameter.
Your use of variables is what is confusing you. The actual issue is not setting t to zero every time you call reverse, but you should think about how you use variable scoping and what functions actually do. Right now you have 2 procedures, that perform actions on global data. Instead try to formulate the problem using functions that accept arguments, and return a result.
#include <iostream>
using namespace std;
int reverse(int z) {
int t = 0;
int rmd;
while (z != 0) {
rmd = z % 10;
t = t * 10 + rmd;
z/= 10;
}
return t;
}
int palin(int z) {
return z == reverse(z);
}
int main() {
int a, b;
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
while (a <= b) {
if (palin(a)) {
cout << a << endl;
}
a++;
}
system("pause");
return 0;
}
Related
#include <bits/stdc++.h>
using namespace std;
int fun()
{
static int num = 16;
return num--;
}
int main()
{
for(fun(); fun(); fun())
cout<< fun()<<" ";
return 0;
}
Output : 14 11 8 5 2
How does the condition (expression-2) of the for loop work? I mean, why does it terminate when fun returns 0 (num becomes -1)?
The condition statement is evaluated before entering the body of the loop. In your case, the statement evaluates to true, and the loop body is executed, if fun() returns a non-zero value.
To see this clearly, modify your code as follows:
int fun( const char* name)
{
static int num = 16;
cout << name << ":" << num << "\n";
return num--;
}
int main()
{
for(fun("init"); fun("test"); fun("iterate"))
cout<< fun("body")<<" ";
return 0;
}
This post treats the same error, but the poster isn't have trouble with a void function.
This post concerns the "void" type of function, but the poster is advised to change the function type to "string", which does not help my case.
My code executes fine, except for a literal "0" at the end of the output. When I change the function type to "void", I am met with the above error.
I have been through the tutorial on this numerous times, and have searched thoroughly, yet have been unable to resolve this issue.
//my code
#include <iostream>
using namespace std;
int intervalcountdown (int a, int b) {
for(a; a>0; a = a - b) {
cout << a;
if(a<=b) {
break;
}
cout << ",";
}
cout << ".";
return 0;
}
int main () {
cout << intervalcountdown(20,3);
return 0;
}
Just don't print what you don't want.
#include <iostream>
using namespace std;
void intervalcountdown (int a, int b) { // change return type to void
for(; a>0; a = a - b) { // meaningless a is removed
cout << a;
if(a<=b) {
break;
}
cout << ",";
}
cout << ".";
// remove the return statement because the return type is now void
}
int main () {
intervalcountdown(20,3); // remove extra printing
return 0;
}
I would like to take the return value from the function on the top and then do something with it in the function on the bottom. What should I put in the bottom function to use the value that was returned from "loadVectorWithReturn"
I do realize that I could create a new variable and store it there for later recall but I am trying to do more complicated things now.
Thank you
double vectors1::loadVectorWithReturn() {
vectors1 v1;
for (int i = 0; i <= 10; i++) {
v1.value.push_back(i);
cout << v1.value[i] << ", ";
}
cout << endl;
cout << v1.value[5] << endl;
return v1.value[5];
}
double doSomethingWithVectorReturn(TAKE IN VALUE FROM loadVectorWithReturn) {
//do something with v1.value[5];
}
If you are saying, "I don't want to make a global variable for v1", you could do this.
double vectors1::loadVectorWithReturn() {
vectors1 v1;
for (int i = 0; i <= 10; i++) {
v1.value.push_back(i);
cout << v1.value[i] << ", ";
}
cout << endl;
cout << v1.value[5] << endl;
return v1.value[5];
}
double vectors1::doSomethingWithVectorReturn() {
int returned = loadVectorWithReturn();
//Do something with returned.
}
Note: the "vectors1::" in front of "doSomethingWithVectorReturn" allows "doSomethingWithVectorReturn" to use the "loadVectorWithReturn" function.
Keep in mind that if you are only using the "returned" value one time (or multiple although that can be slower in many cases), you could skip setting the variable and just use "loadVectorWithReturn()" in place of it.
Example (Simply cout's the value):
double vectors1::doSomethingWithVectorReturn() {
cout << loadVectorWithReturn();
}
I am feeling like you are needing this because you will use loadVectorWithReturnlater within doSomethingWithVectorReturn in some point.
If this is the situation we can use:
#include <iostream>
#include <functional>
struct A
{
int fooA() const
{
return 5;
}
};
void doSomethingWithA( std::function<int()> foo )
{
std::cout << foo();
}
int main()
{
A a;
doSomethingWithA([a]()
{
return a.fooA();
});
}
I'm having some problems with my program which I do not understand.
On line 72, I get the error: "error C4700: uninitialized local variable 'sumInEuros' used" however surely it is initialized as I am using it to store a calculation?
Also on line 66 I get "error C4716: 'showPriceInEuros': must return a value" - why must this return a value? the function is simply meant to output a message to the console.
I'm using VS13 and it's c++.
Any help would be very much appreciated, because I am stuck!
Thanks!
#include <iostream> //for cin >> and cout <<
#include <cassert> //for assert
#include <iomanip> //for endl
#include <Windows.h>
using namespace std;
void processAPrice();
int getPriceInPounds();
int convertPriceIntoEuros(int pounds);
int showPriceInEuros(int pounds, int euros);
int calculateSum(int euros);
void produceFinalData(int sum, int numberOfPrices);
int main()
{
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
processAPrice();
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
if (numberOfPrices > 0)
//produceFinalData(sum, numberOfPrices);
system("PAUSE"); //hold the screen until a key is pressed
return(0);
}
void processAPrice() //
{
int pounds = getPriceInPounds();
int euros = convertPriceIntoEuros(pounds);
int sum = showPriceInEuros(pounds, euros);
calculateSum(euros);
}
int getPriceInPounds() //
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
return priceInPounds;
}
int convertPriceIntoEuros(int priceInPounds) //
{
const int conversionRate(0.82);
return priceInPounds / conversionRate;
}
int showPriceInEuros(int pounds, int euros) //
{
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
void produceFinalData(int sum, int numberOfPrices) //
{
SetConsoleOutputCP(1252);
cout << "The total sum is: \u20AC" << sum;
cout << "The average is: \u20AC" << (sum/numberOfPrices);
}
Well, the showPriceInEuros function is not returning the int it promises to return in its signature. That's the error.
If the function is not supposed to return a value, you should declare its return type as void:
void showPriceInEuros(int pounds, int euros);
//^^
and then:
void showPriceInEuros(int pounds, int euros) {
SetConsoleOutputCP(1252);
cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}
of course.
surely it is initialized as I am using it to store a calculation?
The calculation is based on the variable's uninitialised value:
sumInEuros = (sumInEuros + euros);
^^^^^^^^^^ not initialised
Perhaps you could declare it static, so that its value is preserved between calls to the function, in order to calculate the sum of all the values you pass to the function. Usually, it would be better to use a class to manage persistent data like this, with member functions to update and access it.
why must this return a value?
Because you say it does:
int showPriceInEuros(int pounds, int euros)
^^^
If it shouldn't return a value, change the return type to void.
You do not initialize sumInEuros in this function. You store a result in it - that's true but to calculate the result you are using the uninitialized value.
int calculateSum(int euros) //
{
int sumInEuros;
sumInEuros = (sumInEuros + euros);
return sumInEuros;
}
Answering the question from below:
I would probably create a class PriceCalculator which has all the functions of your algorithm plus the internal state:
class PriceCalculator {
int m_sumInEuros;
public:
PriceCalculator()
: m_sumInEuros(0) { }
void processAPrice(int price);
int getSumInEuros() const { return m_sumInEuros; }
private:
void updateSum(int priceInEuros);
};
From your main function you should create an object of this type and give it the prices you want to sum. Do not do any console input from your class.
int main()
{
PriceCalculator calc;
char answer('Y');
int numberOfPrices(0);
while (answer = 'Y')
{
int priceInPounds;
cout << "Enter a price (in Pounds): /234";
cin >> priceInPounds;
calc.processAPrice(priceInPounds);
numberOfPrices++;
cout << "Continue? (Y/N)";
cin >> answer;
}
...
You might want to think about adding the numberOfPrices to your calculator class as well. At the end you will do all the operations in your class but the user input and console output outside your class. Your class can be tested automatically this way and is completely independent from the user interface.
I am completely newbie to C++. I am doing a practice which consists of building a very simple C++ program.
My teacher emphasizes that it must use recursion with functions and methods. I am wondering how to use recursion within a method in C++. I was looking for some code examples but I haven't find anything. My deep concerns are how a method calls itself without not knowing the name of its class/instance.
class Foo
{
public:
Foo(int offset) : offset(offset) {}
int bar(int x)
{
if (x == 0)
{
return offset; // Base-case
}
return x + bar(x-1); // Recursion
}
private:
int offset;
};
int main()
{
Foo foo(7);
std::cout << foo.bar(5) << "\n"; Prints "22" (5+4+3+2+1+7)
}
Wikipedia: Recursion
I guess your homework is to write a Recursive Descent Parser. A simple example in C:
uBASIC
An example:
#include <iostream>
using namespace std;
int factorial(int n) // 1, 1, 2, 6, 24, 120, 720, ...
{
if (n == 0) return 1;
return n * factorial(n-1);
}
main()
{
int n = 7;
cout << "Enter a non-negative integer: ";
cin >> n;
cout << "The Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}
You can find more examples here : http://www.cstutoringcenter.com/tutorials/cpp/cpp6.php