The product is not calculated correctly [closed] - c++

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 3 years ago.
Improve this question
I wrote code to evaluate the expression above. It executes, but I suspect that the expression is not evaluated correctly.
#include <iostream>
#include <math.h>
using namespace std;
int main(){
setlocale(0, "");
// Задание 1
cout << "Задание 1" << endl;
cout << "" << endl;
double m, x, k, k1, k2;
int n = 18;
cout << "Определите m: ";
cin >> m;
cout << "Определите x: "; // вероятно, в задании ошибка. Если не положу ничего в x - там будет
//единица, ответы будут примерно одинаковые.
cin >> x;
do // начало цикла do while
{
k2 = pow(x, 3*x+1);
k1 = k2 * (8*x);
k = k1 - 785;
}
while (n < m); // конец цикла do while
cout << "Результат вычисления, k = " << k << endl;
system("pause");
}

If you want to use a loop instead of calling std::pow, you have to fix its condition and iteration expression. The calculations inside the body are also different from the posted formula. Note the following changes:
double k = 1.0;
for (int i = n; i <= m; ++i)
{ // ^^^^^^^^^^^^^^^
k *= pow(x, 3.0 * x + 1.0) + 8.0 * x;
// ^^ ^^^
}
k -= 785.0; // <- This should be outside
Note that the body of the for loop doesn't depend on i, so that there are plenty of ways to refactor this code in more efficient ways.

Related

Why this two codes have a different output? [closed]

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 9 months ago.
Improve this question
why this code below have a different output, would you like to explain it ?
input :
10
3 2
4 2
1 1
1 2
1 3
9 3
9 11
9 12
9 1000
8 11
Code #1 :
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
ll t , limak_max , bob_max , limak_total = 0, bob_total = 0;
cin >> t;
while(t--){
cin >> limak_max >> bob_max;
int i = 1;
while(1){
if(i&1){
limak_total += i;
}
else{
bob_total += i;
}
if(limak_total > limak_max){
cout << "Bob" << '\n';
break;
}
else if(bob_total > bob_max){
cout << "Limak" << '\n';
break;
}
i++;
}
}
}
Code #2 :
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
ll t , limak_max , bob_max , limak_total , bob_total;
cin >> t;
while(t--){
cin >> limak_max >> bob_max;
limak_total = 0;
bob_total= 0;
int i = 1;
while(1){
if(i&1){
limak_total += i;
}
else{
bob_total += i;
}
if(limak_total > limak_max){
cout << "Bob" << '\n';
break;
}
else if(bob_total > bob_max){
cout << "Limak" << '\n';
break;
}
i++;
}
}
}
Well, just look at where the two codes differ. For Code #2 there are these two lines:
limak_total = 0;
bob_total = 0;
Code #1 does not contain these two lines.
In between different iterations of your while(t--), which I'm assuming to be your different testcases, Code #1 does not reset limak_total and bob_total, which you use when determining your output. Code #2 does.
Therefore they have different outputs.

find prime numbers up to n digits using only 1 loop statement [closed]

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 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am new in programming and trying to solve some questions and in this question, I am trying to find prime numbers up to n digits using only 1 loop statement.
One loop, and recursion:
#include <iostream>
#include <cmath>
#define NUDIGS 3 //number of digits
bool TestPrime(int n, int ndiv)
{
if ( n == ndiv )
return true;
if ( (n % ndiv) == 0 )
return false;
return TestPrime (n, ++ndiv) ;
}
int main()
{
//calculate the max number with BUDIGITS
int max = pow(10, NUDIGS) - 1;
std::cout << "testing numbers from 2 to " << max << std::endl;
int ntot = 0;
//Loop testing every number. '1' is not considered as a prime number.
for (int i=2; i <= max; i++)
{
//call a recursive test
if ( TestPrime(i, 2) )
{
std::cout << i << " is prime " << std::endl;
ntot++;
}
}
std::cout << ntot << " prime numbers found" << std::endl;
}
//this program will print prime number from 2 to N . and break loop
without using break statment
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int range;
cin>>range;
int num=2;
for(int i=2;i<=num;i++){
if(num>range){
i=num+1;
}
else{
if(i==num){
cout<<num<<" ";
i=1;
num=num+1;
}
else if(num%i==0){
i=1;
num=num+1;
}
}
}
cout<<endl;
return 0;
}

C++ Can't retrieve private variable from class [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am writing a program that generates integers and sets the range of the user's choosing.
For example:
Enter the number of integers: 4
Range: 10
4 9 2 1 are generated
Now the user chooses 4 digits at a time until they're correct.
Program will also tell user if they are partially correct.
For example:
User input: 4 9 0 7
Console << 2 of your answers are correct.
I have three files:
Driver.cpp
#include <iostream>
#include "Game.h"
using namespace std;
int main()
{
// Declare variables.
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) {
cout << "Enter the Number of Integers (n): " << endl;
cin >> numberOfIntegers;
cout << "Number of Each Integers from 1 to (m): " << endl;
cin >> rangeOfIntegers;
cout << "Enter your guesses for the " << numberOfIntegers << " integers in the range from 1 to " << rangeOfIntegers << " that have been selected:" << endl;
guess.beginGuessingGame(rangeOfIntegers, numberOfIntegers);
}
if (count == numberOfIntegers) {
cout << "You are correct! Play again? (y/n)";
}
else {
cout << count << " of your guesses are correct." << endl;
}
};
Game.h
// identifiers
#ifndef guessing_game
#define guessing_game
class Guess
{
private :
int * generatedSequence;
int * inputGuess;
int sum;
public :
void generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers);
void beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers);
int getSum() {
return sum;
}
};
#endif
and Game.cpp
#include <iostream>
#include <iomanip>
#include "Game.h"
using namespace std;
void Guess::generateSequence(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Initialize random number generator.
srand(time(0));
/// Declare array size for the generated sequence to be based on user input.
generatedSequence = new int[inputRangeOfIntegers];
/// Input randomly generated numbers from from 0 to input range into generatedSequence.
for (int i = 0; i < inputNumberOfIntegers; i++) {
generatedSequence[i] = rand() % inputRangeOfIntegers + 1;
cout << generatedSequence[i] << " " << endl;
}
}
void Guess::beginGuessingGame(int inputRangeOfIntegers, int inputNumberOfIntegers) {
/// Call our generateSequence function.
generateSequence(inputRangeOfIntegers, inputNumberOfIntegers);
/// Declare guess size based on user input.
inputGuess = new int[inputNumberOfIntegers];
/// Begin endless loop for user to guess integers.
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}
}
My issue is: I cant retrieve that sum variable in the main class to check it against the number of integers. Because if they are equal, then the program knows the user has guessed correctly. I cant use cout after calling the beginGuessingGame function either..
Any suggestions?
Thanks.
At least this part of the program
Guess guess;
int numberOfIntegers;
int rangeOfIntegers;
int count = guess.getSum();
//Prompt user input.
while(count != numberOfIntegers) { //...
does not make sense. The program has undefined behavior.
Data members of the class object guess are not initialized So the member function getSum returns an indeterminate value of the data member sum of the object. And this indeterminate value is compared with another indeterminate value of the uninitialized variable numberOfIntegers in the while loop.
In the function generateSequence it seems there is a typo in this statement
generatedSequence = new int[inputRangeOfIntegers];
There should be
generatedSequence = new int[inputNumberOfIntegers];
Within the function beginGuessingGame there is an infinite loop
for (;;) {
for (int i = 0; i < inputNumberOfIntegers; i++) {
cin >> inputGuess[i];
}
/// If the user has found the random sequence, we can make sum equal to the number of integers.
sum = 0;
for (int i = 0; i < inputNumberOfIntegers; i++) {
for (int j = 0; j < inputNumberOfIntegers; j++) {
/// If the user has entered the right guess, we can tally sum to the number of integers entered.
if (generatedSequence[i] == inputGuess[j]) {
sum++;
break;
}
}
}
}

A number in the mirror algorithm in C++ [closed]

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
I am trying to write an algorithm which can show me the number I enter in the mirror. I mean, if I enter 173, it should show me that the number in the mirror is 371. I wrote the code, but something it's not working and I can't figure what. Thanks a lot !
#include <iostream>
using namespace std;
void Citire(int &n)
{
cout << "\nda numarul:";
cin >> n;
while (n <= 0)
{
cout << "ai gresit, da natural:";
cin >> n;
}
}
int Oglinda(int &n)
{
int Og = 0;
int UltCif;
while (n > 0)
{
UltCif = n % 10;
Og = Og * 10 + UltCif;
n = n / 10;
}
return Og;
}
int main()
{
int n;
int Og;
Citire(n);
Oglinda(Og);
cout << endl << Og << " este oglinda numarului " << n << endl;
return 0;
}
I think you mean:
Og = Oglinda(n);
And that function's signature should be:
int Oglinda(int n);
Otherwise, you're modifying n in the function - which you don't want to do since you want to print its original value at the end.

For loop to find out solution? [closed]

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 9 years ago.
Improve this question
Problem:
How many times does it take for one person to carry all items? Person can carry 'carryWeight' kg of weight each time.
My solution:
int main()
{
int a = 40; // 1st item weight
int b = 35; // 2nd item weight
int c = 20; // 3rd item weight
int maxItemWeight = a; // Max weight item.
int times; // Times to carry all the items
int carryWeight; //How much weight a person can carry at once
cin >> carryWeight;
if (maxItemWeight > carryWeight)
cout << "It's impossible to carry all the items " << endl;
else {
if((a + b + c) <= carryWeight)
times = 1;
else if ((a+b) <=carryWeight && (a+c) <=carryWeight && (b+c) <=carryWeight)
times = 2;
else
times = 3;
cout << "Times to carry all the items: " << carryWeight << endl;
}
return 0;
}
Solution is simple, but if you have to add more variables it gets complicated. Is it possible to use an array and some loop to get a solution for any number of variables?
It appears you are asking if you can use an array to allow for any number of "items" to be carried. The answer is yes:
std::vector<int> item_weights;
unsigned int item_count = 0;
std::cout << "Enter item count: ";
std::cin >> item_count; // I'll leave the error checking to you to implement
for (unsigned int i = 0; i < item_count; ++i)
{
std::cout << "Enter weight for item " << (i + 1) << ": ";
unsigned int w = 0;
std::cin >> w; // again error checking should be added
item_weights.push_back(w);
}
// insert code to retrieve maximum weight that can be carried here
unsigned int max_weight = std::max_element(item_weights.begin(), item_weights.end());
unsigned int total_weight = std::accumulate(item_weights.begin(), item_weights.end(), 0);
// insert your code to determine the number of times it would take to carry all items here