This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 9 years ago.
I have written a program but it always gives the same number (41).
Why does not it change next time I play?
Second question is: How can I limit the answer between 2 numbers?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int magic,guess;
char ans='y';
magic=rand();
printf("\t\t\tgame(guess the number)\n");
do{
printf("guess the magic number\n");
scanf("%d",&guess);
if(guess==magic){
printf("\n*****Right*****\n");
printf("%d is the magic number.",magic);
getch();
ans='n';
}else{
printf("\n*****Wrong*****\n");
if(guess>magic)
printf("your guess is too high\n");
else printf("your guess is too low\n");
printf("do you want to continue?\n");
ans=getch();
}
}while(ans=='y');
return 0;
}
I want to limit answer between 50 and 500. How can I do that?
put srand (time(NULL)); as the very first line of your main() function and let the magic start :)
now .... rand() gives you number in the range 0 to RAND_MAX
so lets say you want to limit it between x and y(inclusive)(x < y)
then int rand_num = rand() %(y-x+1) + x; would be your solution
Cheers :)
Seed the random number generator with srand - http://www.cplusplus.com/reference/cstdlib/srand/
Use something like the process ID and/Or the current time
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
How do i make this program counts how many dozen in a number and also count its extra amount?
This is what only I came up
#include<stdio.h>
int main()
{
float number, dozen;
printf("Please Enter any integer Value : ");
scanf("%f", &number);
dozen = number / 12;
printf("dozen of a given number %.2f is = %.2f", number, dozen);
return 0;
}
I dont know how i will get to count the dozen in a number, for example there is 45, i need to get 3 dozen and the extra will be 9.
You prompt for an integer but then use floats. You already had the correct dozen calculation and just miss the modulo operator %. Reformatted code for readability.
#include <stdio.h>
int main() {
printf("Please Enter any integer Value : ");
int number;
scanf("%d", &number);
printf("dozen of a given number %d is %d with remainder %d\n",
number,
number / 12,
number % 12
);
return 0;
}
and example execution:
Please Enter any integer Value : 14
dozen of a given number 14 is 1 with remainder 2
Now that there is an accepted answer,
here's a small lesson in arithmetic (plagiarising #Allan Wind's answer):
#include <stdio.h>
int main() {
printf("Please Enter any integer Value : ");
int number;
scanf("%d", &number);
printf("dozen of a given number %d is %d with remainder %d\n",
number,
number / 12,
number - ( number / 12 * 12)
);
return 0;
}
This question already has answers here:
Is floating point math broken?
(31 answers)
The most efficient way to implement an integer based power function pow(int, int)
(21 answers)
Closed 2 years ago.
#include<stdio.h>
#include<math.h>
int main()
{
int n, num, sum=0, count=0, a, remain=0;
printf("Enter a number : ");
scanf("%d", &num);
a=num;
n=num;
while(a!=0)
{
a=a/10;
count++;
}
while(n!=0)
{
remain=n%10;
sum=sum+pow(remain, count);
printf("%d\n", sum);
n=n/10;
}
if(sum==num)
printf("Armstrong Number");
else
printf("Not an Armstrong Number");
return 0;
}
guys I am trying to make a program of checking if a number is Armstrong number or not. And I am facing this problem with '153' as an input specifically. The program works fine with various inputs but compiler is showing unusual behavior while adding 153. I will also attach the output with different inputs explicitly showing the addition of numbers in the 'sum' variable.
OUTPUT:
Enter a number : 153
27
151
152
Not an Armstrong Number
Enter a number : 371
1
344
371
Armstrong Number
pow returns a double, which means you could have weird rounding issues. You may want to consider implementing your own integer exponentiation function.
This question already has answers here:
How to generate a random int in C?
(32 answers)
Closed 6 years ago.
If I want to create a username generator in C? How do I go about it? I do understand that the question has been asked. But, I don't see anyone asking it in C language.
I think making it from a random word from the dictionary is going to be a little complicated for me to understand. I am right now only going to concentrate on a simple thing, and that is GENERATING 4 RANDOM NUMBERS. Now, before anyone says it's not secure or anything, this is purely for my curiosity and tinkering experience! I am enjoying learning C and I want to learn more.
The code that I have been able to come up with (minus the generator!) is as follows:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int randomnumbers; // this is for storing whatever random numbers I may generate
char NAME[15];
prinf("What is your first name? \n");//
scanf("%s \n", NAME);// I put it caps so that I can easily see it
printf("The username for %s is %s%d \n",NAME,NAME,randomnumbers);
return 0;
}
In case you find that the code is lacking and is of poor taste, I apologise. I am a newbie with less than a week in experience in coding. I thank you for your help and guidance.
rand is what you need.
int randomnumbers = rand();
You may also want to read on how to seed the random number generator
Bonus random username generator:
// buffer must have memory for len + 1 elements
void generateUserName(/*out*/ char *buffer, int len)
{
srand(time(NULL));
int idx = 0;
while (idx < len) buffer[idx++] = rand() % 26 + 'a';
buffer[len] = '\0';
}
To be called as
char userName[10];
generateUserName(userName, sizeof(userName) - 1);
printf("%s\n", userName);
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 8 years ago.
Improve this question
Only the second code is good,but i don't understand why!
Just tell me what is the difference between line with factorial if it is before or after the printf
#include <stdio.h>
int main(int argc, char *argv[]) {
int numar;
printf("introdu un numar:");
scanf("%d",&numar);
int factorial = 1;
for (int i = 1; i <= numar; i++) {
printf("%d * %d =%d\n" , factorial,i,factorial*i);
factorial = factorial * i;
}
}
second code:
#include <stdio.h>
int main(int argc, char *argv[]) {
int numar;
printf("introdu un numar:");
scanf("%d",&numar);
int factorial = 1;
for (int i = 1; i <= numar; i++) {
factorial = factorial * i;
printf("%d * %d = %d\n", factorial, i, factorial*i);
}
}
The second code is actually wrong. It gives me 5! = 600, but that's not right. The first code shows 120 as it should, and everything looks nice.
The reason the first is right is because it shows the current value staged to multiply with the next number, and showing the resultant calculation before you actually do it. The second is wrong because it does the calculation, and does it correctly, but then displays the calculation done over again...so you will get the right factorial, but you won't printf the right values.
Actually the first sample of your code should display the correct values. Because in the second one, the value displayed is multiplied by the index i twice (even though the value of factorial doesn't change the second time you multiply it).
Consider this example - when i is 3 and factorial is 2:
First code will print "2*3 = 6", then will multiply factorial by 3, so at the end of the iteration factorial is 6.
Second code will multiply factorial by 3, so now factorial is 6. Then it will print "6*3 = 18" - the operation is not correct for factorials, even though the result is. There is no number which has its factorial equal to 18. However, factorial still holds the value 6. It's just the printed operation that is incorrect.
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 8 years ago.
Improve this question
I am trying to get a duration of time into minutes from a string. I am given a string like this: "1:50". And I need to extract the minutes and seconds from this strings into int variables and then return the duration in minutes. So I wrote this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
int main()
{
char time[6]="01:30";
int duration=0, minutes=0, seconds=0;
int buffermin[3];
int buffersec[3];
int i=0;
while(i<2)
{
sscanf(time[i],"%d%d",&buffermin[i]); //Get the first two characters in the string and store them in a intger array
i++;
}
i=3;
while(i<5)
{
sscanf(time[i],"%d%d",&buffersec[i]); //Get the last two characters in the string and store them in a integer array
i++;
}
printf("%d %d %d %d", buffermin[0], buffermin[1], buffersec[0], buffersec[1]);
getch();
minutes=(buffermin[0]*10)+buffermin[1]; //Put values in array to one variable
seconds=(buffersec[0]*10)+buffersec[1]; //Same as above
seconds=seconds/60; //Turn the number of seconds to minutes
duration=seconds+minutes; //Get total duration
printf("The total duration is: %d\n",duration); //Output total duration
getch();
exit(0);
}
Why is this not working and how could I fix this. Any examples would be really very appreciated. If you have the time to explain how the example works, please do so. Still poor at programming as you can see.
You should really learn how to use sscanf properly. Basically, what you want to achieve is this:
#include <stdio.h>
int main() {
char time[] = "01:27";
int minutes;
int seconds;
// Must be double, not integer, otherwise decimal digits will be truncated
double duration;
// String has format "integer:integer"
int parsed = sscanf(time, "%d:%d", &minutes, &seconds);
// Check if input was valid
if (parsed < 2) {
// String had wrong format, less than 2 integers parsed
printf("Error: bad time format");
return 1;
}
// Convert to minutes (mind the floating point division)
duration = (seconds / 60.0) + minutes;
printf("Duration: %.2f minutes\n", duration);
return 0;
}