I'm currently going through the CS50 course and already hit the first obstacle. Basically I am trying to check different conditions to be true in order for an output, however even if what I am introducing is correct, it just seems to not work.
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int test = 0;
double nr = get_double("Your card number please:\n ");
while(test < 1)
{
if(nr / 100000000000000 < 10)
{
if(nr / 10000000000000 == 37)
{
printf("AMEX");
test++;
}
else if(nr / 10000000000000 == 34)
{
printf("AMEX");
test++;
}
}
else {
printf("false");
}
}
}
Here is an example that should work:378282246310005. Even if I introduce a wrong number, nothing is being displayed.
Also, I reckon the while loop is not breaking because the conditions aren't run, or is there another mistake I am missing?
Thanks in advance peeps
You are using a double (a representation of a floating point number that need not be an integer), meaning that when you divide it by your divisors, the result is not truncated. For your example (input is 378282246310005), the value of nr / 10000000000000 is not 37, but is actually a double with value approximately 37.8282246...
The input will not fit into an int, so the get_int function available in cs50.h will be inappropriate. However, the value will fit into a long, on the environment that CS50 uses1
Declare nr with type long, and use get_long() to obtain the input from the user. Then the value of nr / 10000000000000 will be truncated toward zero to become 37, exactly as you need here.
Note regarding types:
1 The authors of libcs50 document get_long() with a 64-bit signed type for long in mind, having the expected toolchain and environment in mind. This is not always the case, especially if your environment (OS, compiler, etc) doesn't match what the authors of CS50 expect you to use.
You will want to make sure that your assumptions hold if you want to use long on other environments; it is unwise to generalize that long will be 64 bits in the future, without first carefully verifying that this is the case. For the purposes of this assignment, the given type will be sufficient, but you may want to consider learning about the stdint.h header, which provides types that have a guaranteed, specified size.
Related
This is a simple test program where I am trying to get the result "12 angry men" shown on the console after I complete taking inputs to get into the sub genre from the 2nd printf of the program. what have i done wrong here? please don't try to find relevance with anything here. The console will simply ask the user to press 1 for action then it'd ask Humorous/Other, when humorous would show 12 angry men after taking input as 1.1.
int main()
{
int action=1,comedy=2;
float humorous=1.1, other=1.2,input1;
int input;
printf("Which Movies You Want to See\n");
printf("Action/Comedy");
scanf("%d",&input);
if(input==1)
{
printf("Humorous/Other");
scanf("%f",&input1);
if(input1==1.1)
{
printf("12 angry men");
}
}
return 0 ;
}
Like others have mention, it is not good practice to directly compare floats like you are trying to do. For example, if you set int input1 = 1.1 and then try to use printf("%f", input1), the output is 1.10000 or something similar. This will not return true for 1.1 == 1.10000 in C at run time which is what is causing the issue.
You could just use different integers to case into what you want to happen depending on the input, or (if you really, really must) you can compare using the < and > operators. Ie if (input1 > 1.09 && input1 < 1.11).
This will give you the desired result.
You want to compare floats, so you want to do the following:
if(input1==1.1f)
{
/* Will be true if the user inputs 1.1 */
}
and not
if(input1==1.1){}
You should never test a binary floating-point number for exact equality to a decimal real value. A 32-bit float can represent a finite number of discrete values few of which coincide with an exact decimal value die to the binary rather then decimal floating-point encoding.
It is probably a bad idea to to floating point values for "menu selection" in any event, but if you insist, your code can be fixed thus:
if( fabs(input1 - 1.1) < 0.01 )
It also happens to work if you avoid the unnecessary implicit conversion from float to double:
if( input1 == 1.1f )
but that is still ill-advised in general - it will not work for all values.
If I wanted to limit the range of values to be assigned to an integer to three different conditions. eg; Must be between 9 and 95 and also be divisible by 5 would this be the correct way to accomplish this?
I've been told that i can have multiple conditions as long as they are separated by && but I am having little success with my code.
if (input >= 5 && input <= 95 && input %5)
Your code seems fine to me, except for this line.
if (input >= 5 && input <= 95 && input %5)
The expression input % 5 returns the remainder of input/5. You want input to be divisible by 5, which happens when input % 5 returns a remainder of 0. Since C interprets 0 as false, and pretty much all other integers as true, this expression will do exactly the opposite of what you want it to do. Try using
if (input >= 5 && input <= 95 && (input % 5 == 0))
That should do what you want it to do.
There are a number of issues with your code as it stands. First, the outright bugs:
The expression input % 5 will give you the remainder when divided by five. This means you will get zero if it is a multiple, non-zero otherwise. Unfortunately, zero is treated as false so this will only be true if input is not a multiple. The correct expression is (input % 5) == 0.
If you enter something that cannot be interpreted as an integer, the scanf will fail and input will be left at whatever value it was beforehand. This should be caught and acted upon, by checking the return value - this gives you the number of items successfully scanned so should be one.
Your code seems to return the value if okay but return nothing if it's invalid.
Next, while not bugs, these things are my personal preferences which can make code easier to read and maintain:
I prefer to explicitly separate sub-expressions so I never have to worry about precedence rules (provided it doesn't make the expression unreadable in the process). To that end, I would make the full if statement if ((input >= 5) && (input <= 95) && ((input % 5 == 0)).
I'm not a big fan of the if (condition) transferControl else ... construct since the else is totally superfluous.
I also prefer error catching to be done in a localised fashion at the start, catching problems early. Only after all checks are passed do you do the success portion.
A function (assuming it is a function, which seems likely) should generally do one thing, such as check if the value is valid. Writing issues to standard output is probably best left to the caller so that the function is truly re-usable. It would be better to have a function do the check and return some value to indicate whether or not there was a failure, along with the value if valid.
It's usually better to use puts("something") rather than printf("something\n"). The printf call is best left to where you actually need to do argument formatting.
Taking that all into account, the code that I would posit would be along the lines of:
#include <stdbool.h>
bool InputValidRangeAndMultiple(
unsigned *pValue,
unsigned minVal,
unsigned maxVal,
unsigned multVal
) {
unsigned input;
// If no unsigned int available, error.
if (scanf("%u", pValue) != 1) return false;
// If value invalid in any way (range or multiple), error.
if ((*pValue < minVal) || (*pValue > maxVal)) return false;
if ((*pValue % multVal) != 0) return false;
// Value is now deemed okay.
return true;
}
Calling that function can be done thus, with the prompts and errors handled outside the "input and check" function:
#include <stdio.h>
unsigned value;
puts("Enter Value.\nValue must be divisible by 5 and within 5 and 95...");
if (! InputValidRangeAndMultiple(&value, 5u, 95u, 5u)) {
puts("Invalid input...");
returnOrDoSomethingIntelligent();
}
// The 'value' variable is now valid.
I wrote a small program to compute Fibonacci numbers:
#include <stdio.h>
int main()
{
int first, second, final;
first = 0;
second = 1;
printf("0\n1\n"); /* I know this is a quick fix, but the program still works */
while (final <= 999999999999999999) {
final = first + second;
first = second;
second = final;
printf("%d\n", final);
}
}
Is there any way to increase the speed in which this program computes these calculations? Could you possible explain the solution to me (if it exists)?
Thanks.
Of course it's possible! :)
First of all, please note you're using signed int for your variables, and max int on a 32 bit machine is 2,147,483,647 which is approx. 10^8 times smaller than the max number you're using, which is 999,999,999,999,999,999.
I'll recommend to change the max num to INT_MAX (You'll need to include "limits.h")
Edit:
In addition, as said in the comments to my answer, consider changing to unsigned int. you need only positive values, and the max number will be twice higher.
2nd Edit:
That being said, when final will reach the closest it can to the limit in the condition, the next time its promoted, it'll exceed INT_MAX and will result in an overflow. That means here, that the condition will never be met.
Better to just change the condition to the times you want the loop to run. Please note though, that any fibonacci number larger than the max numder that can be stored in your variable type, will result in an overflow.
Secondly, final isn't initialized. Write final = 0 to avoid errors.
I recommend turning on all the warnings in your compiler. It could catch many errors before they compile :)
Also, I see no reason not to initialize the variables when you declare them. The value is already known.
Now for the speed of the program:
I'm not sure to which extent you're willing to change the code, but the simplest change without changing the original flow, is to make less calls to printf().
Since printf() is a function that will wait for a system resource to become available, this is probably the most time consuming part in your code.
Maybe consider storing the output in a string, and lets say every 100 numbers print the string to the screen.
Try maybe to create a string, with a size of
(10 (num of chars in an int) + 1 (new line char) )* 100 (arbitrary, based on when you'll want to flush the data to the screen)
Consider using sprintf() to write to a string in the inner loop, and strcat() to append a string to another string.
Then, every 100 times, use printf() to write to the screen.
As already stated in other answers, you have obvious two problems. 1) The missing initialization of final and 2) that your loop condition will result in an endless loop due to 999999999999999999 being larger than any integer value.
The real problem here is that you use a fixed number in the condition for the while.
How do you know which number to use so that you actually calculates all the Fibonacci numbers possible for the used integer type? Without knowing the numbers in advance you can't do that! So you need a better condition for stopping the loop.
One way of solving this to check for overflow instead - like:
while (second <= (INT_MAX - first)) { // Stop when next number will overflow
The above approach prevents signed overflow by checking whether the next first + second will overflow before actually doing the first+second. In this way signed overflow (and thereby UB) is prevented.
Another approach is to use unsigned integers and deliberately make an overflow (which is valid for unsigned int). Using unsigned long long that could look like:
unsigned long long first, second, next;
first = 1;
second = 1;
printf("1\n1\n");
next = first + second;
while (next > second) { // Stop when there was an overflow
printf("%llu\n", next);
first = second;
second = next;
next = first + second;
}
Speed isn't your problem. You have an infinite loop:
while (final <= 999999999999999999) {
final has type int. Most likely int is 32-bit on your system, which means the maximum value it can hold is 2147483647. This will always be smaller than 999999999999999999 (which is a constant of type long long), so the loop never ends.
Change the datatype of your variables to long long and the loop will terminate after about 87 iterations. Also, you'll need to change your printf format specifier from %d to %lld to match the datatype printed.
Why are you asking this question?
If it's the intention to increase the performance, you might go for the formula of the n-th Fibonacci number, which is something like:
((1+v5)/2)^n + ((1-v5)/2)^n, something like that (v5 being the square root of 5).
If it's about learning to increase performance, you might do a code review or use performance diagnostics tools.
I am extremely new to programming in general, so please forgive my noobishness. I am trying to scale down the res[?] array in the function below. I know the problem that the res[?]*(multiplier/100) is creating a decimal answer instead of the required format which is an integer therefore I need to convert the result before it is plugged into the res[?].
I did think of turning res[] array into a double but I wasnt sure whether the initwindow(?,?) was compatible with integer values.
I am on mingw with code blocks. the linker and compiler has customized setting made by my professor. I am on Plain\basic C???
I tried to apply the techniques this website used about the truncating conversion. But doesn't seem to work. http://www.cs.tut.fi/~jkorpela/round.html
Debugger watcher shows that res[?] is equivalent to 0.
#include <stdio.h>
#include <graphics_lib.h>
#include <math.h>
int res[2]//contains a array which contains the vertical and horizontal detected resolution from main()
void function(res)
{
printf("Please note the lowest resolution available is 800x600\n");
printf("Please enter percentage ratio % below 100:");
scanf("%d",&multiplier);
res[1]=(int)(res[1]*(multiplier/100));
res[2]=(int)(res[2]*(multiplier/100));
blah blah blah blah.............
initwindow(res[1],res[2]) //from custom header that my professor made which initializes basic graphics window
return;
}
I'm assuming multiplier is an int to match the %d format.
multiplier/100 is guaranteed to be zero (if the user follows directions and provides a number less than 100). You can do (res[x]*multiplier)/100 to make sure the multiply happens first (you're probably okay without the parentheses, but rather than think about order of operations why not be explicit?)
The cast to int is unnecessary, because an int divided by another int is always an int.
Unless your professor has done some very interesting things, you should also note that a two-element array such as res would have elements res[0] and res[1], not res[1] and res[2].
you don't need to cast in this situation because the conversion is done implicitly . you only need a cast to assign the content of a variable to a variable of different type .
Looks like the multiplier variable is an int, so the result of multiplier/100 expression will be 0 in all cases.
Also, it's a good programming practice to check the validity of user's input.
You must declare multiplier before you use it:
int multiplier;
printf("Please note the lowest resolution available is 800x600\n");
printf("Please enter percentage ratio % below 100:");
scanf("%d",&multiplier);
And the index is staring from 0 not 1. And you should initialize res[0] and res[1] before using them. So:
res[0] = 800;
res[1] = 600;
And the division of multiplier by 100 will truncate to 0, try this without casting as it will be automaticly converted:
res[1]=(multiplier*res[0])/100;
res[1]=(multiplier*res[1])/100;
I want to write some code which takes any positive, even number (greater than 2) and gives me the smallest pair of primes that sum up to this number.
I need this program to handle any integer up to 9 digits long.
My aim is to make something that looks like this:
Please enter a positive even integer ( greater than 2 ) :
10
The first primes adding : 3+7=10.
Please enter a positive even integer ( greater than 2 ) :
160
The first primes adding : 3+157=160.
Please enter a positive even integer ( greater than 2 ) :
18456
The first primes adding : 5+18451=18456.
I don't want to use any library besides stdio.h. I don't want to use arrays, strings, or anything besides for the most basic toolbox: scanf, printf, for, while, do-while, if, else if, break, continue, and the basic operators (<,>, ==, =+, !=, %, *, /, etc...).
Please no other functions especially is_prime.
I know how to limit the input to my needs so that it loops until given a valid entry.
So now I'm trying to figure out the algorithm.
I thought of starting a while loop like something like this:
#include <stdio.h>
long first, second, sum, goldbach, min;
long a,b,i,k; //indices
int main (){
while (1){
printf("Please enter a positive integer :\n");
scanf("%ld",&goldbach);
if ((goldbach>2)&&((goldbach%2)==0)) break;
else printf("Wrong input, ");
}
while (sum!=goldbach){
for (a=3;a<goldbach;a=(a+2))
for (i=2;(goldbach-a)%i;i++)
first = a;
for (b=5;b<goldbach;b=(b+2))
for (k=2;(goldbach-b)%k;k++)
sum = first + second;
}
}
Have a function to test primality
int is_prime(unsigned long n)
And then you only need to test whether a and goldbach - a are both prime. You can of course assume a <= goldbach/2.
And be sure to handle goldbach = 4 correctly.
If the requirements don't allow defining and using your own functions, ignore them first. Solve the problem using any functions you deem helpful and convenient. When you have a working solution using disallowed functionality, then you start replacing that with allowed constructs. Self-defined functions can be inlined directly, replacing the return with an assignment, so instead of if (is_prime(a)), you have the code to determine whether a is prime and instead of returning the result you assign it is_prime = result; and test that variable if (is_prime). Where you have used library functions, reimplement them yourself - efficiency doesn't matter much - and then inline them too.