I'm learning C programming and I've encountered a problem using scanf for initializing values into the array. In this example, 10, 32 and 20 were input as values for the array; 20 should be in grades[2] but its value is 0.
Why doesn't the program register the last value that is input?
That is the relevant code.
I'll appreciate any help in understanding what went wrong with the program.
#include <math.h>
#include <stdio.h>
#include <stdbool.h>
#define N 50
#define MaximalSTD 10
int main() {
printf("Please enter the grades of the examinees");
printf(" followed by the expected mean\n");
double grades[N], ReqMean;
int numgrade = 0;
for (int i = 0; i < N; i++) {
if (scanf("%lf", &grades[i]) == 1) {
numgrade++;
} else
break;
}
ReqMean = grades[numgrade - 1];
printf("numgrade: %d\nReqMean: %d\n", numgrade, ReqMean);
return 0;
}
printf("numgrade: %d\nReqMean: %d\n" , numgrade,ReqMean);
You are using the wrong format specifier for a double value (ReqMean in this case).
Try Instead.
printf("numgrade: %d\nReqMean: %lf\n" , numgrade,ReqMean);
Related
#include<stdbool.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
double InputNum; //needs to be double for test cases
int NumLoops = 11; // loops runs 11 times
printf("Enter number please: ");
scanf_s("%lf", &InputNum);
for (int i = 0; i < InputNum; --NumLoops) //incrementally goes down
{
if (isdigit(InputNum))
{
printf("%lf\n", InputNum+1);
}
else
{
printf("Must be a number!");
exit(EXIT_FAILURE);
}
}
return 0;
}
program incrementally increases by one starting at user's input, this happens 11 times and than ends program, unfortunately it does not do that and keeps printing out the else statement in this code, Any suggestions?
So the problem is that scanf() is converting the integer you enter to a double. So when you type an int for example 5, will be converted to 5.00000, and isdigit() will not convert this to a digit so it always fails.
This is how I would do it.
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
double InputNum; //needs to be double for test cases
int NumLoops = 11; // loops runs 11 times
printf("Enter number please: ");
scanf("%lf", &InputNum);
for (int i = 0; i < NumLoops; ++i)
{
if ((InputNum - floor(InputNum)) == 0)
{
printf("%f\n", InputNum+1);
}
else
{
printf("Must be a number!");
exit(EXIT_FAILURE);
}
}
return 0;
}
I apologize if the title is misleading in anyway, because I don't know where or how to start on this one.
Recently I wrote a math game that makes random numbers and turns them into equations. But all the program can do Is take in numbers, if I wanted to allow commands like say show-stats to show your stats. I have to write the command and then a number after for the command to get recognized like so
show-stats 0
score is 1
show-stats
0 //number is required for some reason
score is 1
This is a minimal example I wrote
#include <stdio.h>
#include <string.h>
int main() {
int bar;
char foo[]="";
int score = 1;
scanf("%s%i",foo,&bar);
if(strcmp(foo,"show-stats"))
{
printf("Score is %i",score);
}
if(bar == 2)
{
score = bar*2;
printf("Doubled Points.\n");
}
}
Here is the actual code, In case you need. Also, I'd like advisors on the actual code, like if its spaghetti or if something is performance consuming, or just what I can improve on in general if its not too much trouble. thanks in advance and I'm open to suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define VER 10
#define DIV "-----"
int main()
{
system("clear");
unsigned int x,y; //equation numbers
int ans,sum; //user answer
unsigned int max = 10; //max possible number that can be made, cannot go under 10.
int score; //what do you think?
char operation;
int correctAnswers = 0,wrongAnswers = 0;
printf("Math game\nVersion %i.\n",VER);
for (; ;)
{
//phase 1; make numbers.
srand(time(NULL));
x = rand() % max;
y = rand() % max;
//phase 2; make operation type.
operation = rand() % 2;
switch (operation)
{
case 0:operation = '+';sum = x + y;break;
case 1:operation = '-';sum = x - y;break;
}
//phase 3; write question to console and get user answer
printf("What is %i %c %i? ",x,operation,y); //get input
scanf("%i",&ans);
//phase 4; determine right answer
if (ans == sum)
{
score++;
correctAnswers++;
max++;
printf("Your correct! +1!\n");
printf("%sStats%s\nScore:%i\nMax possible number:%i\nCorrect Answers:%i\nWrong Answers:%i\n%s%s%s\n",DIV,DIV,score,max,correctAnswers,wrongAnswers,DIV,DIV,DIV); //print stats when user wins,is a seperate call for readability. same thing on line 53 but for loss
}
else
{
score--;
wrongAnswers++;
if(max>10){max--;}; //assures max doesn't go under 10
printf("Wrong! -1\n");
printf("%sStats%s\nThe correct answer was %i\nMax possible number : %i\nScore : %i\nCorrect Answers : %i\nWrong Answers : %i\n%s%s%s\n",DIV,DIV,sum,max,score,correctAnswers,wrongAnswers,DIV,DIV,DIV);
}
}
}
Thanks to DevSolar, I know how to do this. Using fgets() and strtol() you can collect the entire string, and parse it into the command and the number, I read up on strtol here https://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
edit:
char str[30] = ""; //the string the user types
fgets(str,30,stdin);
char *ptr; //the part of the string turned into words
long ret; //the part of the string turned into numbers
ret = strtol(str, &ptr, 10); //parameter 1;source string that is parsed;//parameter 2; string part of source.//parameter 3; base
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);
i am trying to write a program such that if a % 2^j = 0 then it prints 1 , else it prints 0 so at the end i get a 16 bit binary code. But i get no error and after i enter an input number (a) terminal crashes.
Thank you for your help.
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
uint16_t a, j, b, mod;
printf(" Please insert a number between 0 and 65535 \n ");
scanf("%d", &a);
j = 16;
while (j > 0)
;
{
b = pow(j, 2);
mod = a % b;
if (mod == 0) {
printf("%d", 1);
} else {
printf("%d", 0);
}
j = j - 1;
}
return 0;
}
You have undefined behavior as you use the %d format for scanf. This format specifier expects the argument to be a pointer to int.
Mismatching format specifier and argument type leads to UB.
For uint16_t use the macro SCNu16 (as documented in e.g. this reference):
scanf("%" SCNu16, &a);
Write a program that displays a new random permutation of the integers 0 to 9 at the request of its user. For example, the program’s output could be as follows:
Your program should prints how many 7 was printed when user type no.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int i , total , r;
char ans;
srand(time(NULL));
do{
for( i=0 ; i < 10 ; i++)
{
r= (rand()%(9-1+1)) + 1;
printf ("%d ",r);
}
total =0;
if (r==7) // Here how can I correct this so total will increase every time
{ // there is a 7 in the string
total++;
}
printf("\nAnother permutation: y/n?\n");
scanf(" %c",&ans);
if (ans != 'y')
{
printf("Bye!\n");
printf("The number of 7's is: %d", total);
}
}while(ans=='y');
return 1;
}
I have a problem with my code. How can I increment the 7's shown in this program after != 'y'.
Set total=0 before entering into the do-while loop, to get the correct total.
I'm having some issues on my code to get the highest number on an array of 5 elements, this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float timerunner1[4];
int x;
int main() {
for(x=1;x<6;x++) {
printf("Give me the time of runner 1: ");
scanf("%f",timerunner1[x]);
}
return 0;
}
This works perfectly, the output is:
Give me the time of runner 1: 14
Give me the time of runner 1: 3
Give me the time of runner 1: 10
Give me the time of runner 1: 5
Give me the time of runner 1: 2
How can I get the highest and lowest number of the array?
Maybe using a for or if.. How?
Thanks!
It doesn't work actually, you need to use the address of operator '&' to store the value in the array.
scanf("%f", &timerunner1[x]);
Also, your array isn't large enough to store the 6 integers that your loop is requiring and subscripting of an array starts at zero and ends at 5 (for 6 elements).
You can then either have another loop AFTER reading all your values to calculate the maximum or calculate it on the fly as below:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float timerunner1[6];
int x;
float maximum = 0.0f;
int main() {
for (x = 0; x < 6; x++) {
printf("Give me the time of runner 1: ");
scanf("%f", &timerunner1[x]);
maximum = maximum > timerunner1[x] ? maximum : timerunner1[x];
}
printf("%f\n", maximum);
return 0;
}
Also, this code only works on positive values because maximum is initialised to zero and will always be larger than any negative value, if you need negative values, you should be able to experiement and figure that out.
Ok, in this program you will have to load the time of each player manually.
/* StackFlow
Find the highest of an array of 5 numbers */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
float timerunner1[ 5 ] ={ 0 };
float highest;
int highestindex, i;
/* Data input*/
for( i = 0; i < 5; i++ ){
printf( "\nEnter the %d element of the array: ", i );
scanf( %f, timerunner1[ i ] );
}
/* Considering that the first generated number is the highest*/
highest = timerunner1[ 0 ];
highestindex = 0;
/* The first element of an array is [0] not [1]*/
for( i = 1; i < 5; i++ ) {
/* if the next element in the array is higher than the previous*/
if ( highest < timerunner1[ i ]){
highest = timerunner1[ i ];
highestindex = i;
}
}
printf("\nThe highest time of the runner %d is: %f \n", highestindex, highest);
return 1;
}