I am still trying to learn algorithms, I have a homework. I must make an output
Sum of : 1/2 + 1/4 + 1/6 - 1/8 + 1/10 + 1/12
Result : 0.975
But output of my program
Sum of : 1/2 + 1/4 + 1/6-1/8 + 1/10 + 1/12
Result : 0.975
I dont know how to make space negative sign, if i use cout there will show twice negative sign.
my program
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int i ,sign, p, q, n;
double x , S;
S=0;
cout << "Sum of :";
for (i=1; i <= 6; i++)
{
if ( (i % 4 == 0) && ( i > 1 ) ) // to make condition where the number become negative
{
sign = -1;
}
if ( ( i % 4 != 0 ) && ( i > 1 ) ) // to make condition where the number become positive
{
sign = 1;
cout << " + ";
}
if ( i == 1 ) // to prevent 1st number not show " + " symbol
{
sign =1;
}
p = sign*1;
q = ( 2 * ( i - 1 ) ) + 2;
cout << p << "/" << q;
x = ( 1.0 * p / q );
S = S + x;
}
cout << "\n" << S;
}
I realise that my program has too many operations which may be avoided, could u help me make it more effecient ?
So your
cout << p << "/" << q;
will always have that format if p is negative.
Instead (This workaround is intended to be simple)
if(p < 0) {
cout << " - " << p*-1 << "/" << q;
} else {
cout << p << "/" << q;
}
That should do it.
If you are looking to use recursion as you have indicated in the subject, then here is what you can also refer.
static void recurse(int i, int limit){
int sign = 0, p, q, n;
double x, S;
S =0;
if (i == 1) // to prevent 1st number not show " + " symbol
{
sign = 1;
cout << "Sum of : ";
}
else if (i< 1 || i> limit){
return ;
}
else {
sign = (i % 4 == 0) ? -1 : 1;
if (sign > 0){
cout << " + ";
}
else {
cout << " - ";
}
}
p = 1;
q = ( 2 * ( i - 1 ) ) + 2;
cout << p << "/" << q;
x = ( 1.0 * p / q );
S = S + x;
recurse(i+1, limit);
}
Call using:
int main ()
{
recurse(1, 6);
cout << "\n";
}
Related
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.
I need to write a program that takes an integer as input and outputs it with its digits spaced. The algorithm works fine but prints the digits in reverse order. To get the original order, I used a for loop. The problem is that it prints nothing.
#include <iostream>
using namespace std;
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num) ;
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << " Your digits:";
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
return 0;
}
My issue is here
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
It prints nothing. What could be the problem ?
The input used is 1234
The expected output is 1 2 3 4
For starters the function countDigit is wrong.
int countDigit(int n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
It returns 0 for the valid number 0 that has one digit.
The function can look the following way
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
In this loop
for (int i = countDigit(Num); i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
the variable Num was changed. So in the next loop
for (int x = 1 ; x <= countDigit(Num) ; x++)
{
cout << arr[x] << " " ;
cout << sum ;
}
it will not have the original value You need to use an intermediate variable to make the calculation.
Also take into account that the use can enter a negative number.
EDIT: After you updated your code then you also need to move the output of the sum from the loop
for (int x = 1 ; x <= c; x++)
{
cout << arr[x] << " " ;
}
cout << sum ;
And instead of the large integer array it is better to use an object of the type std::string.
Here is a demonstrative program
#include <iostream>
#include <string>
size_t countDigit( int n, int base = 10 )
{
size_t count = 0;
do
{
++count;
} while ( n /= base );
return count;
}
int main()
{
const int Base = 10;
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
size_t count = countDigit( num );
std::string s( count, ' ' );
int sum = 0;
for ( ; count-- != 0; num /= Base )
{
int digit = num % Base;
if ( digit < 0 ) digit = -digit;
s[count] = digit + '0';
sum += digit;
}
std:: cout << "Your digits: ";
for ( const auto &c : s ) std::cout << c << ' ';
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Its output might look like
Enter an integer: -123456789
Your digits: 1 2 3 4 5 6 7 8 9
The sum of digits is 45
Another approach is to write a recursive function that outputs digits and returns the sum of digits.
#include <iostream>
unsigned int recursive_sum( long long int n, long long int base = 10, std::ostream &os = std::cout )
{
long long int digit = n % base;
if ( digit < 0 ) digit = -digit;
unsigned int sum = digit + ( ( n /= base ) == 0 ? 0 : recursive_sum( n ) );
os << digit << ' ';
return sum;
}
int main()
{
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
unsigned int sum = recursive_sum( num );
std::cout << '\n';
std::cout << "The sum of digits is " << sum << '\n';
return 0;
}
Again the program output might look like
Enter an integer: -123456789
1 2 3 4 5 6 7 8 9
The sum of digits is 45
This gives the expected output. I assigned countDigit(Num) to c and wrote the sum to outside the loop.
int main()
{
int Num ;
int sum = 0;
int arr[100];
cout <<"Enter an integer: " ;
cin >> Num ;
int c = countDigit(Num); //edit 1
// extracts the digits
for (int i = c; i > 0; i--)
{
arr[i] = (Num % 10);
Num = (Num / 10);
sum += arr[i];
}
cout << "Your digits with spaces: ";
// reverses the order
for (int x = 1 ; x <= c ; x++)
{
cout << arr[x] << " " ;
}
cout << endl << "The sum of the digits is: " << sum ; // edit 2
return 0;
}
Here's a shorter version:
#include <concepts>
#include <cstdio>
#include <string>
template <std::integral T>
void printDigits(T const i) {
for (auto const ch : std::to_string(i)) {
std::printf("%c ", ch);
}
std::fflush(stdout);
}
LIVE
Here's a take that uses strings.
#include <iostream>
#include <string>
int main()
{
std::string input;
std::size_t location;
std::cout << "Enter an integer: ";
std::getline(std::cin, input);
std::stoi(input, &location); // Don't care about the integer, just location
if (location != input.length()) {
std::cout << "Invalid Entry: Non-integer entered\n";
return 1;
}
for (auto i : input) {
std::cout << i << ' ';
}
// Here's a one liner that requires <algorithm>
// std::for_each(input.begin(), input.end(), [](auto i) { std::cout << i << ' '; });
std::cout << '\n';
}
I don't care about an integer at all. I can validate that only digits were entered and quit early if not. The only loop I need is for printing.
stoi() can return the integer, but I don't care about the integer. I just want to know how many characters were converted, and I learn that by feeding it the output argument location. Checking that location is the same as the string length ensures that only digits were entered. No decimal points, no extra letters, just numbers.
The caveats are that this might not fit into your requirements if this is an assignment. It also requires C++11, which is surprisingly not a given yet (for assignments, I get the industry arguments).
I have already written most of the code for the problem and it works. I'm just unsure of how to format the output.
Problem : Design and develop a C++ program for Calculating e(n) when delta <= 0.000001
e(n-1) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n-1)!
e(n) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n)!
delta = e(n) – e(n-1)
You do not have any input to the program. Your output should be something like this:
N = 2 e(1) = 2 e(2) = 2.5 delta = 0.5
N = 3 e(2) = 2.5 e(3) = 2.565 delta = 0.065
#include <iostream>
using namespace std;
//3! = 3 * 2!
//2! = 2 * 1!
//1! = 1
int factorial(int number)
{
//if number is <= 1, return 1
if (number <= 1)
{
return 1;
}
// otherwise multiply number by factorial(number - 1)
else
{
//otherwise multiply number by factorial(number - 1) and return it
int temp = number * factorial(number - 1);
cout << "factorial of " << number << " = " << temp << endl;
return temp;
}
}
double sumOfFactorials(int n)
{
double sum = 0;
//loop from 1..n, adding the factorial division to a sum
for (int i = 1; i <= n; i++)
{
double dividedValue = 1.00000 / factorial(i);
cout << fixed;
sum = sum + dividedValue;
}
return sum;
}
/**
* Compute the sum of 1 + ... + 1/(n!)
* input number: 1
* output number: 1 + ... + 1/(input!)
*/
double e(int n)
{
double value = 1 + sumOfFactorials(n);
return value;
}
int main()
{
cout << "e:" << e(3) << endl; // 1 + sumOfFactorials(3)
cout << "sumOfFactorials: " << sumOfFactorials(3) << endl; //0 + 1/1! + 1/2! + 1/3!
}
You have the right code, All you need is to format the output. Just modify the main() method. here is a snippet you can try.
NOTE : There is an error in the precision of the answer, I think you can correct it.
PS : Please uncomment your debugging cout lines.
int main()
{
for(int i = 2; i<4; i++){
double en_1 = e(i-1);
double en = e(i);
double delta = en - en_1;
cout << "N = "<<i;
cout << " e("<< (i-1) <<") = " << en_1;
cout << " e("<< (i) <<") = " << en;
cout << "delta = " << delta;
cout << "\n";
}
}
I am trying to create a c++ program that when I input two numbers (num1, combinationNum), it finds two numbers that multiply together to equal num1, but add together to equal combinationNum. It currently works for positive integers, but not negative. How do I make it work with negative integers? Also, If the equation isn't solvable, I would like it to print an error of some sort. Thanks!
Code:
//
// main.cpp
// Factor
//
// Created by Dani Smith on 2/13/14.
// Copyright (c) 2014 Dani Smith Productions. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
void factors(int num, int comNum){
int a, b;
cout<<"The factors are ";
bool isPrime = true;
int root = (int)sqrt((double)num);
for(int i = 2; i <= root; i++){
if(num % i == 0 ){
isPrime = false;
//cout<<i<<",";
for(int x = 0; x<3; x++){
if(x==1){
a = i;
}
else if(x == 2){
b = i;
}
if(a + b == comNum){
cout << a << ", and " << b << ".";
}
}
}
}
//----------------------------------------
if(isPrime)cout<<"1 ";
cout<<endl;
}
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, multiple = 0, combinationNum = 0, output1 = 0, output2 = 0;
cout << "What number do you want to factor?\n";
cin >> num1;
cout << "What do you want them to add to?\n";
cin >> combinationNum;
factors(num1, combinationNum);
return 0;
}
To solve:
x + y == a
x * y == b
You have to solve
y == a - x
x * x - a * x + b == 0
So with delta == a * a - 4 * b, if delta positive, the solutions are
x1 = (a + sqrt(delta)) / 2
x2 = (a + sqrt(delta)) / 2
The code : (https://ideone.com/qwrSwa)
void solve(int sum, int mul)
{
std::cout << "solution for x + y = " << sum << std::endl
<< " x * y = " << mul << std::endl;
const int delta = sum * sum - 4 * mul;
if (delta < 0) {
std::cout << "No solution" << std::endl;
return;
}
const float sqrtdelta = sqrtf(delta);
const float x1 = (sum + sqrtdelta) / 2.f;
const float x2 = (sum - sqrtdelta) / 2.f;
std::cout << "x = " << x1 << ", y = " << sum - x1 << std::endl;
if (delta != 0) {
std::cout << "x = " << x2 << ", y = " << sum - x2 << std::endl;
}
}
I have been trying to finish this code (function) for a while now, but am stuck on the last part. In this code, I prompt the user to select a number of integers and any number of digits and then find the smallest and largest value within these digits. On the next part, I am supposed to determine which of the given digits the smallest and largest are located such that the output should be:
Digit _ can be found in integer number(s): _, _
I apologize in advance if my code is sloppy; I just started learning C++ and haven't fully grasped the language yet.
int digitSizeLoca() {
int userNumInteger;
int* iPtr;
int* iPtr2;
int* iPtr3;
int value;
int value2;
int value3;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
iPtr2 = new int[userNumInteger];
iPtr3 = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++) {
*(iPtr3 + 1) = *(iPtr2 + 1) = *(iPtr + 1);
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + 1);
}
value = *(iPtr + 1);
value2 = *(iPtr2 + 1);
value3 = *(iPtr3 + 1);
if (value != 0, value2 != 0, value3 != 0) {
if (value <= 0)
value = -value;
if (value2 <= 0)
value2 = -value2;
if (value3 <= 0)
value3 = -value3;
int lDigit;
int sDigit;
int curDigit;
int pot = 10;
lDigit = sDigit = value % pot;
while (value, value2, value3) {
if (value / pot == 0, value2 / pot == 0, value3 / pot == 0) break;
curDigit = (value / pot, value2 / pot, value3 / pot) % 10;
if (curDigit < sDigit)
sDigit = curDigit;
if (curDigit > lDigit)
lDigit = curDigit;
pot*=10;
}
std::cout << "\nThe smallest digit: " << sDigit << std::endl
<< "\n Digit " << sDigit
<< " can be found in integer number(s): ";
std::cout << "\nThe largest digit: " << lDigit << std::endl
<< "\n Digit " << lDigit
<< " can be found in integer number(s): ";
}
return 0;
}
Example of what output should be given user input:
If user chooses 2 for userNumInteger, and inputs the digit values 1234 and -1578,
the output for my question should be:
Smallest digit: 1
Digit 1 can be found in integer number(s): 1, 2
.
.
.
Thank you!
If digits matter, then input 02 is not the same as 2 (even if both means the number 2; beware that 02 could be an octal notation). So you should read a std::string, check that it has digits appropriately using isdigit, then use std::stol (in C++11) or strtol to do the conversion.
You'll better use some std::vector<int> instead of initializing a pointer with new int[userNumInteger] ...
Since you mentioned that you can only use integer for now, it makes your life a bit difficult. Basile was right when he mentioned that you should use string. That would help you iterating through the numbers over and over again like I did below but it does the task - the drawback being that you will have to iterate 3 times but if you do not want to sort or do anything special then it is good enough....
int digitSizeLoca()
{
int userNumInteger;
int* iPtr;
int lowest = 9;
int highest = 0;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++)
{
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + i);
}
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
std::cout << "You Entered (" << i << "): " << *(iPtr + i) << std::endl;
do
{
int remainder = number % 10;
if (remainder > highest) highest = remainder;
if (remainder < lowest) lowest = remainder;
number = number / 10;
}
while (number > 0);
}
std::cout << "\nThe largest digit: " << highest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == highest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
std::cout << "\nThe smallest digit: " << lowest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == lowest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
}