I have a program which takes an unsigned long int as an input, and all subsequent functions should receive the value as such.
In the main function, however, when 18446744073709551557 is entered, it is returned as 34359738363435973836, and when the value is passed to another function, it is seen as 3435973836.
How come this happens?
EDIT:
Main function is as follows:
int main()
{
// initalise variables
std::list<unsigned long int> results;
unsigned long int n;
// request user input
std::cout << "Enter a number: ";
std::cin >> n;
std::cout << "You entered: " << n << std::endl;
// populate results list
results = primeFactors(n);
results.sort();
// display results
std::cout << "Factors for " << n << " are: ";
for (int i : results)
{
std::cout << i << " ";
}
return 0;
}
Function the value gets passed into:
std::list<unsigned long int> primeFactors(unsigned long int n)
{
// initialise variables
std::list<unsigned long int> factors;
bool complete = false;
unsigned long int ans1 = 0;
unsigned long int ans2 = 0;
std::cout << n;
(There's a lot of code in the second function, so I haven't included it all)
Your input number is far too large to store as an unsigned long int.
You can view the limits for various types here
I would suggest looking into using a library that can handle arbitrarily large numbers such as Boost.multiprecision
I don't think that 18446744073709551557 is a valid unsigned long int.
It crosses the limit already.
The limit of c++ datatype are here...
Try the value between limits. If then also doesn't work help us to see the code snippets and to detect the bugs.
Related
I'm a beginner in programming and as you can see, I created a program where the user is asked to input three numbers. It will display the greatest among the numbers given. But after I finished the code, a question came into my mind, what if the user was asked to input a hundreds of numbers and should display the greatest among the numbers given. So the question is, is it possible to do that? what are the things I need to learn to produce that result? is there any hints you can give me?
#include <iostream>
#include <string>
using std::cout, std::cin, std::endl, std::string;
int main() {
string result = " is the greatest among the numbers given";
double x, y, z;
cout<<"Enter three numbers to decide which is the largest: "<<endl;
cin >>x;
cin >>y;
cin >>z;
system("clear");
if(x>y && x>z){
cout<< x << result;
} else if (y>z && y>x){
cout << y << result;
} else
cout<< z << result;
return 0;
}
With the program below, you can get as many numbers as you want from the user and find the largest of them.
#include <iostream>
int main()
{
int size=0, largestValue=0, value=0;
std::cout << "Enter total numbers you want to add :" << "\n";
std::cin >> size;
for (int i{ 0 }; i < size; ++i)
{
std::cout << "Enter value to add : ";
std::cin >> value;
if (i == 0 || value > largestValue)
{
largestValue = value;
}
}
std::cout << "Largest value = " << largestValue << "\n";
return 0;
}
One solution would be to store your inputs in a list and sort them afterwards. Just google "sorting alorithms". Also there are nice youtube visualizations.
Another one would be to not save the inputs into dedicated variables - in your case x, y, z - but to always save the largest given input:
int largestInput = std::numeric_limits<int>::min();
int input;
for (int i = 0; i < 10000; i++)
{
std::cin >> input;
largestInput = input > largestInput ? input : largestInput;
}
If you know the inputs are large, you can use vectors.
#include <bits/stdc++.h>
using namespace std;
int main(){
int total_num=0;
cout << "Enter total numbers:" << "\n";
cin>>total_num;
int max_number = INT_MIN;
vector<int> v;
for(int i=0;i<total_num;i++){
int x;
cin>>x;
v.push_back(x);
max_number = max(max_number,x);
}
cout<<"Maximum number present: "<< max_number<<endl;
return 0;
}
Although there is no need to store numbers. But it's your choice if you need it later you can use it in that program.
> what are the things I need to learn
what if the user was asked to input a hundreds of numbers
For this, you'll need to learn about arrays. I suggest you first learn about C-style arrays (int x[3]{};), and then std::array (std::array<int, 3> x{};). You also need to learn about loops.
and should display the greatest among the numbers given
Having to find the largest number in an array is very common. If you want to learn how to do so manually, the other answers here should answer your question. Otherwise, look towards the standard library algorithms std::ranges::max() (C++20) and std::max_element.
Examples
Example 1
Here's a program that uses a C-style array and a simple algorithm to get the largest number:
#include <iostream>
int main(){
// Amount of numbers user should input
constexpr int count{ 3 };
std::cout << "Enter " << count
<< " numbers to decide which is the largest:\n";
// The numbers entered by the user
double numbers[count]{}; // Declare and zero-initialize a C-style array of 3 ints
// Get each number from the user and put it in the array
for (int i{ 0 }; i < count; ++i) {
std::cin >> numbers[i];
}
// The biggest number found so far
int max{ numbers[0] }; // Initialize it with the first number
for (int i{ 1 }; i < count; ++i) { // Start at the second element (element 1)
if (numbers[i] > max) { // If the current number is larger than max...
max = numbers[i]; // ...assign it to max
}
}
std::cout << max << " is the greatest among the numbers given\n";
return 0;
}
Note:
int numbers[count]{};
This creates a C-style array called numbers which has count (3) elements. The first element's "index" is 0 and the last element's is 2. The {} initializes the values of all of the numbers to 0 (good practice).
for (int i{ 0 }; i < count; ++i)
std::cin >> numbers[i];
This loops until i isn't less than count (3) and increments i (++i) each time. It starts at 0, so it loops 3 (0 1 2) times. On each iteration, it gets a number from the console and stores it in numbers[i].
Example 2
Here's a shorter program that uses the standard library:
#include <algorithm> // ranges::max()
#include <array> // array<>
#include <iostream> // cin, cout
int main() {
// Amount of numbers user should input
constexpr int count{ 3 };
std::cout << "Enter "
<< count
<< " numbers to decide which is the largest:\n";
std::array<double, count> numbers{}; // Declare an array of 3 ints
for (int i{ 0 }; i < count; ++i) {
std::cin >> numbers[i];
}
// Return the largest number in array "numbers"
std::cout << std::ranges::max(numbers)
<< " is the greatest among the numbers given\n";
return 0;
}
Note:
std::array<int, count> numbers{};
Declares an array of count (3) ints and zero-initializes it.
std::ranges::max(numbers)
This neat function finds the largest number in numbers. It was added in C++20 -- if you're using an older compiler, you should use *std::max_element(numbers.begin(), numbers.end()). If you want to learn how the latter works, you need to learn about iterators and pointers.
Here are some good practices that your tutorial hasn't taught you yet (if it ever will):
DON'T use using namespace std. It's unsafe because it brings everything in the standard library into global scope. The standard library contains a lot of commonly used identifiers like count and list. Bringing these into global scope is dangerous because it can cause naming conflicts.
Don't use copy initialization (int x = 3). Use uniform/brace/list initialization instead (int x{ 3 }). The former sometimes makes an unnecessary copy, whereas the latter doesn't. The latter also refuses to do narrowing conversions (e.g. initializing a short with a long).
Always initialize variables (do: int x{}, don't: int x), even when it seems redundant. If you don't, then the value stored is undefined - it could be anything. Undefined behaviour is hard to debug but luckily easy to avoid.
Use \n instead of std::endl. Both do the same, except std::endl does an extra buffer flush which is slow and unnecessary. \n is shorter anyways.
DRY -- Don't Repeat Yourself. You have the string " is the greatest among the numbers given" three times in your code. You could have stored it in a std::string instead -- then it wouldn't have repeated.
Repeating code is bad, because:
It's harder to read
It's harder to maintain (you would have to modify it everywhere it's repeated)
Maintenance is more error-prone
If I were you, I'd immediately find a different tutorial/book. See this thread.
#include <stdio.h>
int main()
{
int num1, num2, num3, num4;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("Enter num3\n");
scanf("%d",&num3);
printf("Enter num4\n");
scanf("%d",&num4);
if(num1>num2 && num1>num3 && num1>num4){
printf("greatest number is %d",num1);
}
if(num2>num3 && num2>num1 && num2>num4){
printf("greatest number is %d",num2);
}
if(num3>num1 && num3>num2 && num3>num4){
printf("greatest number is %d",num3);
}
if(num4>num1 && num4>num2 && num4>num3){
printf("greatest number is %d",num4);
}
return 0;
}
I'm writing a C++ program that converts a decimal number to binary and hexadecimal.
The problem is that for some reason it concatenates the number "1875954912" to both representations every time.
I've tried a bunch of things - mainly changing up how the program calculates numArrayLength and the for-loop in my decToBase function, but I haven't been able to figure out why this happens yet.
The program is not complete by the way - it doesn't turn integers bigger than 9 into letters for the hex representation yet, but that's not my main concern right now.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
int howManyBitsNeeded(int someNum, int base) {
int numOfDivisions = 0;
while (someNum != 0) {
someNum = floor(someNum / base);
numOfDivisions += 1;
}
return numOfDivisions;
}
int decToBase(int someNum, int base) {
int bitsNeeded = howManyBitsNeeded(someNum,base);
int numArrayLength = bitsNeeded;
int numArray[bitsNeeded];
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
someNum = floor(someNum / base);
bitsNeeded -= 1;
}
for (int k = (numArrayLength-1); k >= 0; --k) {
cout << numArray[(numArrayLength - k)];
}
}
int main() {
int inpNum;
cout << "Enter your number: ";
cin >> inpNum;
cout << "Binary representation: " << decToBase(inpNum,2) << endl;
cout << "Hexadecimal representation: " << decToBase(inpNum,16);
return 0;
}
And here's what the output looks like:
Enter your number: 25
Binary representation: 110011875954912
Hexadecimal representation: 191875954912
Any help would be greatly appreciated!
Your decToBase is declared as returning an int, but it doesn't actually return anything. Your compiler should warn you about this. Since you're not returning anything here, change its return type to void. Then instead of trying to print its return value, simply call the function without printing it:
std::cout << "Binary representation: ";
decToBase(inpNum, 2); // this already prints the number, no need to pass it to std::cout
std::cout << endl;
std::cout << "Hexadecimal representation: ";
decToBase(inpNum, 16);
std::cout << std::endl;
Or of course you can change the function to return the string that you want to print instead of printing it inside the function.
Also, there's an issue here:
int numArray[bitsNeeded];
This is out of range when you try to access it here:
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
And also later when you try to print it. To get rid of this off by one error, you have to change this to
numArray[bitsNeeded-1] = (someNum % base);
And in the output change it to
cout << numArray[(numArrayLength - k -1)];
And while you're at it, instead of having it as a VLA (which isn't part of C++ and only works if the compiler tolerates it), I would recommend a vector:
std::vector<int> numArray(bitsNeeded+1); // include <vector> for this to work
Furthermore, note that integer division is already truncated, so unless you plan to support negative numbers later on, you can silence a warning about implicit double to int conversion by changing this:
someNum = floor(someNum / base);
To this:
someNum /= base;
After calling function the amount_of_people, the variable n remains unchanged. I verified this by outputting the variable after the function call. Do I need a pointer n to function as argument?
int main(){
srand(time(NULL));
bool Appworks = true;
size_t n;
do {
amount_of_people(n); // Entering amount of people HERE! STUCKED HERE.
if (n >= 1) {
DataBase *first = new DataBase[n]; // Creating dynamic structure-array
inputData(first, n);
output(first, n); // Output of entered data
freeUp_memory(first); // Clearing dynamic-alocated memory engaged by early-created pointer
}
else cout << "Error! Wrong amount of people!" << endl;
} while (Appworks);
system("PAUSE");
return 0;
}
Function declaring:
unsigned amount_of_people(int n) {
cout << "Enter how many people u want to enter" << endl;
cin >> n;
return n;
}
I would appreciate any help and explanation(!)
Thanks for your attention.
amount_of_people(n)
does not use the value returned from amount_of_people. n is of no use here because according to the function declaration
unsigned amount_of_people(int n);
n is passed by value. When a parameter is passed by value, the function operates on a copy of the source variable. Changing the copy has no effect on the original. May I suggest instead,
std::size_t amount_of_people() // parameter gone, return type changed to match n in caller
{
std::size_t n; // parameter moved to here and type changed to match return type
std::cout << "Enter how many people u want to enter" << std::endl;
std::cin >> n;
return n;
}
This is then used like
const std::size_t n = amount_of_people();
Side note: Rather than
DataBase *first = new DataBase[n];
strongly consider ensuring that DataBase correctly observes the Rule of Three, Five, or Zero and using
std::vector<DataBase> databases;
rather than a raw allocation. It knows it's size and looks after all of the memory management for you. Documentation for std::vector.
RE "Do I need a pointer to function as argument", either a pointer or a reference.
unsigned amount_of_people(int n) as you wrote it takes an integer n by value, assigns it using cin >> n, and then returns it. Either change your function to
void amount_of_people(unsigned int& n) {
std::cout << "Enter how many people u want to enter" << endl;
std::cin >> n;
}
and call it:
amount_of_people(n);
which takes n by reference, or write
unsigned int amount_of_people() {
unsigned int n;
std::cout << "Enter how many people u want to enter" << endl;
std::cin >> n;
return n;
}
and call it:
n = amount_of_people();
Both styles have uses; the first is, I think, more common in cases where the function has side effects, and so it "outputs" its results into the ref-passed parameters ("out parameters"), while you opt to return from the function a variable indicating whether an error occurred during its execution. The second style is a little more common for pure functions, where the result is always computed successfully based on the inputs with no possibility of error.
Also, make up your mind whether you want the variable to be a size_t or an int.
In C++, I want to print the first n prime numbers (for this example let's assume n=1000).
In order to do this, I've found mpz_nextprime from the GMP library.
I'd assume you use it like this
int n = 2;
for(int i = 0; i < 1000; i++) {
n = mpz_nextprime(n);
cout << n << endl;
}
but this doesnt compile as mpz_nextprime takes two mpz_t arguments.
How can you use mpz_nextprime in this context?
The reason for mpz_nextprime using mpz_t instead of normal integer types like int or long is that after a certain point the prime numbers will be too large to be representable in a int or long.
Here's a snippet of code to print all up to the 1000th prime number:
#include <gmp.h>
int main() {
mpz_t n;
mpz_init(n);
mpz_set_ui(n, 2);
for (size_t i = 0; i < 1000; i++) { // first 1000 primes
mpz_nextprime(n, n);
cout << "The " << (i + 1) << "th " << " prime is " << mpz_get_ui(n) << endl;
}
}
Note that this code will only work up to a certain prime number because in order to print it, we convert it to an unsigned int using mpz_get_ui here.
If you want to print larger prime numbers, use mpz_get_str (but don't forget to free() the string if you use NULL as first parameter).
I am working in a project and in a certain time I have this problem. I have two very large numbers and I want to divide them and get an integer/long long integer. This is what's happening:
Code
#include <iostream>
using namespace std;
int main(){
long long n,m;
cin >> n >> m;
cout << n/m << endl;
}
The inputs can be numbers until 100,000,000,000,000,000 so the division is performing wrong.
Output
#1 n: 76543210987654321 m: 7654321
#2 76543210987654321/7654321 = 1410312449
The right answer is 10,000,000,130 so I am wondering what is happening...
The correct result is neither 1410312449 nor 10000000130. It is equal to 10000000129
At least it is what the GCC shows at www.ideone.com. You can try it yourself.
#include <iostream>
int main()
{
long long n = 76543210987654321;
long long m = 7654321;
std::cout << n / m << std::endl;
return 0;
}
It seems that you place the result of the operation in an object of type int. Consider the following code
#include <iostream>
int main()
{
long long n = 76543210987654321;
long long m = 7654321;
int x;
x = n / m;
std::cout << n / m << std::endl;
std::cout << x << std::endl;
return 0;
}
The output is
10000000129
1410065537
It seems, that the result of division is truncated to 32-bit value (int).
Try to use explicit cast to long long via static_cast.
Also, it is interesting to know result of sizeof(long long) on your compiler.