I am trying to submit an answer given on codechef "https://www.codechef.com/problems/FLOW009"
this is my code.
#include <stdio.h>
int main()
{
int t, i;
scanf("%d",&t);
i=t;
float qty[t], per[t], sum[t];
do{
scanf("%f %f", &qty[t-1], &per[t-1]);
sum[t-1] = qty[t-1] * per[t-1];
if(qty[t-1] > 1000 )
{
sum[t-1] = sum[t-1] - (sum[t-1]*10)/100;
}
}while(--t);
do{
printf("%f\n", sum[i-1]);
}while(--i);
return 0;
}
It tells me again again that my solution is wrong and I am unable to understand it.I can't ask questions there as I have less karma.
Two things:
Never store values for each test cases until told as sometimes the test cases may be large ,in place calculate and print output for each test cases. This may save memory ,time and confusion.
What could be done with few lines why to do with too much code and mess.
See this:
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int p,q;
scanf("%d %d",&q,&p);
float ans=(float)q*p;
if(q>1000)
ans-=(ans/10);
printf("%f\n",ans);
}
return 0;
}
You cannot scan an int as a string. The sscanf() funtion scans a string according to the specified format string. This code could use more error checking.
$ cat FLOW009.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv)
{
char aline[100];
int t;
int quantity;
int price;
FILE *fh = fopen("FLOW009.txt", "rt");
if (fh == NULL) {printf("open failed"); exit(1);}
if (fgets(aline, 80, fh) != NULL) {
sscanf(aline, "%d", &t);
if (t < 1 || t > 1000) {
printf("ERROR: Value of t, %d, is outside the range 1 to 1000\n", t);
exit(1);
}
while (fgets(aline, sizeof(aline), fh) != NULL) {
sscanf(aline, "%d %d", &quantity, &price);
if (quantity > 0 && price <= 100000) {
printf("%.6f\n", (float)quantity * (float)price);
} else {
printf("ERROR: Quantity and price are not within accepted limits.\n");
}
}
}
exit(0);
}
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 got stucked with the function double ascii_to_float. My function should receives a string of char and give it the value as a double back. I´m not allowed to use atof().
I want to search for a the point in the string, to proof it if its a double. if not it should return -1.
double ascii_to_float(char *textzahl)
{
int x;
double ausgabe;
sprintf(ausgabe,"%s",textzahl);
/* here with -=48, i´m not sure how to code
it right, i just now that i have to decrease with 48.*/
for(x=0; x< strlen(textzahl); x++)
{
if(textzahl[x]=='.')
{
textzahl[x]-=48;
}
else
{
textzahl[x]=-1;
}
}
return ausgabe;
}
The main function is given, so I have to just Write the code of above function.
#include <stdio.h>
#include <string.h>
int main()
{
char text[80];
double zahl2;
printf("\n bitte eine Zahl eingeben:"),
fgets(text, sizeof(text), stdin);
zahl2= ascii_to_float ( text);
if (zahl2==-1.0)
{
printf("\nfehlerhafte Eingabe oder Wert -1");
}
else
{
printf("\ndie Zahl2 lautet: %lf\n",zahl2);
}
}
I didn't follow your terminologies means name of variables, functions... as it is time consuming for me.
Code
#include<stdio.h>
#include<string.h>
double fun(char*);
int main()
{
char str1[]="2356.23", str2[]="234", str3[]="bonap.art" ,str4[]="33.42.2";
printf("%lf, %lf, %lf, %lf", fun(str1),fun(str2),fun(str3),fun(str4));
}
double fun(char *s)
{
int count=0;
int i;
for(i=0; i<=strlen(s)-1; i++)
{
if(s[i]=='.')
{
count++;
}
if(count==2)
{
return -1;
}
if( !((s[i]>=48 && s[i]<=57)|| (s[i]=='.')) )
{
return -1;
}
}
if(count==0)
{
return -1;
}
double d;
sscanf(s,"%lf",&d);
return d;
}
Output
2356.230000, -1.000000, -1.000000, -1.000000
If you see code carefully you understand all. Still I explain some things.
you mentioned that to check given string is double or not you are checking . it contains point or not but that's not enough.
what if string contain 2 . (points) or characters like a, b, *,... So To take care of these two problems I added count, !((s[i]>=48 && s[i]<=57)|| (s[i]=='.')) these conditions respectively. I will not elaborate if you not understand still, you can comment.
I don't understand why you choose sprintf(ausgabe,"%s",textzahl); rather than sscanf(s,"%lf",&d);
Also you can consider strtod float strtod (const char* str, char** endptr); for your question. you can check out here and here
I want to use a function to scanf up to 10 values for an array with the size 10, and also keep track of the number of values that are in the array because I'll need it later for solving some maths about the array, (max value, min value, etc.).
#include <stdio.h>
int enter(int MeasurmentData[], int nrOfmeasurments)
{
for(int i=0;i<10;++i)
{
int MeasurmentData[10];
scanf("%d",&MeasurmentData[i]);
int nrOfmeasurments = 0;
nrOfmeasurments ++;
return nrOfmeasurments;
}
int main()
{
int MeasurmentData[10];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n");
printf("v (View)\n");
printf("e (Enter)\n");
printf("c (Compute)\n");
printf("r (Reset)\n");
printf("q (Quit)\n");
printf("enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') \\ enter values
{
int MeasurmentData[10];
int nrOfmeasurments;
enter(MeasurmentData, nrOfmeasurments);
}
else if(menuoption == 'v') \\\ view values
{
//printf("%d", MeasurmentData[]);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
return 0;
}
}
}
When I run the program it should print Measurment tool 2.0, after the the user has the choice of inputting e(enter) which will scan in up to 10 values into an array, if the user clicks q(quit) while in the enter option already he will be returned to the main menu where he can do whatever.
V(view) prints out the array for the user so that he can view what elements are inside.
C(compute) uses the elements inside and the nr of elements to calculate the highest value element, lowest.
There are some errors in your code. Ill try to explain. You have over declared your variables too many times. And since you have a fixed loop you don't need to count the measurements you will always read 10 measurements.
Below are the code with some modifications. Feel free to ask anything about it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXIMUM_MEASURMENT 10
int enter(int MeasurmentData[])
{
char input[100];
int nrMeasurement = 0;
// reseting Measurment data
for(int i=0;i<MAXIMUM_MEASURMENT;++i) MeasurmentData[i] = 0;
for(int i=0;i<MAXIMUM_MEASURMENT;++i)
{
scanf("%99s", input);
if(strcmp(input, "q") == 0) {
break;
}
MeasurmentData[i] = (int) strtol(input, (char **)NULL, 10);
nrMeasurement++;
}
return nrMeasurement;
}
void showMeasurments(int* MeasurmentData, int length) {
int i = 0;
printf(" ======== Measurment ======== \n");
for(i = 0; i < length; i++) {
printf("%d ", MeasurmentData[i]);
}
printf("\n");
}
int main()
{
int MeasurmentData[MAXIMUM_MEASURMENT];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n" "v (View)\n" "e (Enter)\n" "c (Compute)\n" "r (Reset)\n" "q (Quit)\n enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') // enter values
{
enter(MeasurmentData);
}
else if(menuoption == 'v') // view values
{
// show
showMeasurments(MeasurmentData, MAXIMUM_MEASURMENT);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
break;
}
}
return 0;
}
Edit: i have updated the code. So i have read the comments of your question and there you have explained a little better what you are trying to accomplish. So since you have the requirement to press 'q' to stop reading values. I have to read all measurments as string and convert to integer if it is not the character q.
Edit 2: Thanks to #user3629249 to point out some of the flaws from the code ill update with his suggestions.
I have a problem with C program. The idea of it is similar to Armstrong number checking. Say if the input number is 123. Program needs to check if condition, for example 123=1^1+2^2+3^3 is true. I know how to add digits,but have a problem with powers. It is obvious that I need a loop for powers from 1 to the number of digits. In Armstrong number algorithm you have similar power on every digit. For example 153=1^3+5^3+3^3. Here is what I have so far:
#include<stdio.h>
int main()
{
int n,d,s=0,o,i,k;
printf("n=");scanf("%d",&n);
d=n;
while(d!=0)
{
o=d%10;
s=s+o;
d=d/10;
k++
}
printf("sum:%d",s);
printf("number of digits:%d",k);
return 0;
}
Thanks for the answers.
You need first get the lenth of number, which is used to determine how many times you need to get into loop to calculate each bit.
For example, number 123, you first need to know the number is 3 bits len, then you can mutilply number 3 three times, number 2 twice, and number 1 once.
I use a temporary string to achieve this
here is code, a little bit alteration on yours
#include <stdio.h>
#include <string.h>
#define MAX_NUM_LEN 16
int main()
{
char tmp_num[MAX_NUM_LEN] = {0};
int len,n,d,s=0,o,i,tmp_len, tmp_o;
printf("n=");scanf("%d",&n);
sprintf(tmp_num, "%d", n);
len = strlen(tmp_num);
tmp_len = len;
d=n;
while(d!=0)
{
o=d%10;
for (tmp_o = 1, i = tmp_len; i > 0; i--)
tmp_o *= o;
s=s+tmp_o;
d=d/10;
tmp_len--;
}
printf("sum:%d\n",s);
printf("number of digits:%d\n",len);
return 0;
}
results:
According of what I've understood I think this is what the OP is looking for:
int power(int base, int exp)
{
if (base == 0) return 0;
int result=1;
while (exp-- > 0) result*=base;
return result;
}
void calculate(int number)
{
int d=number;
int tmpnumber=number;
int n=0;
while (d > 0)
{
n++;
d /=10;
}
printf("Number of digits: %d\n", n);
int k=0;
int sum=0;
while (n--)
{
// get digits from left to right
d=number / power(10, n);
k++;
sum+=power(d, k);
number %= power(10, n);
printf("%d^%d=%d\n", d, k, power(d, k));
}
printf("\n%5d %5d", tmpnumber, sum);
}
int main(int argc,char *argv[])
{
int value;
while (TRUE)
{
printf("Enter value (0 = Quit): ");
scanf("%d", &value);
if (value <= 0) return 0;
calculate(value);
printf("\n");
}
}
I am currently working on a project for school in which I need to program a calculator to determine the mode of a set of numbers. The parameters are the numbers have to be between 1 and 30. Have to check whether the user inserts a number within that range and that the number must be validated as an integer. I have most of it done except my main issues are the for loop in inputing the numbers and validating them and making sure my mode function works. Any suggestions in fixing the issue with the loop? Also I must use a mode function in order to calculate the mode does the one I'm using work well or is there a better way in going about it?
#include <stdio.h>
#include <string.h>
#include <math.h>
int mode(int *num, int size);
int main(int n, char **p) {
int modearray[], size, i;
printf("What is the size of the Array?");
scanf("%d", &size);
for (i=0; i<modearray[size]; i++) {
printf("Enter an integer value (1 to 30): ");
scanf("%d", modearray[i]);
if (modearray[i] < 1 || modearray[i] > 30) {
printf("Please enter a value within the range");
scanf("%d", modearray[i])
}
else if (sscanf(p[i], "%i", &a[i]) != 1) {
printf("ERROR\n");
return -1;
}
}
}
//used the mode function code frome http://www.dreamincode.net/forums/topic/43713- pointers-and-modefunction/
int mode(int *num, int size) {
int currentnum = (*num);
int count = 0;
int modenum = -1;
int modecount = 1;
for (int x=0; x<size; x++) {
if (currentnum==(*num + x)) count ++;
else {
if(count > modecount) {
modenum = currentnum;
// modecount = count;
x--;
}
currentnum=*(num + x);
count = 0;
}
}
}
As Charlie and user2533527 have already indicated, there are errors in the OP code, and they have offered suggestions regarding those errors. There are a few others that I have noted in my edit of your original code below, that without addressing, the code did not build and/or run. So, if you are interested, look at the inline comments at the bottom of this post to see some corrections to your original code.
This answer is focused on validation of input, per your stated objective ( Have to check whether the user inserts a number within that range and that the number must be validated as an integer ) Specifically it appears you need to verify that the numbers input fall within a range, AND that they all be an integers.
If you move all of the validation steps into one function, such as:
int ValidateInput(char *num)
{
if(strstr(num, ".")!=NULL) return FLOAT;
if (atoi(num) < 1) return SMALL;
if (atoi(num) > 30) return LARGE;
return VALID;
}
then the main user input loop can be easily executed to include specific errors, if any, or continue with data collection by using a switch() statement, such as:
status = ValidateInput(number);
switch(status) {
case VALID:
modearray[i] = atoi(number);
printf("Enter an integer value %d: (1 to 30): ", i+2);
break;
case FLOAT:
printf("float detected, enter an integer");
i--;//try again
break;
case SMALL:
printf("value too small, enter value from 1 to 30");
i--;//try again
break;
case LARGE:
printf("value too large, enter value from 1 to 30");
i--;//try again
break;
default:
//do something else here
break;
}
Altogether, this approach does not use the mode function, rather replaces it with ValidateInput() which ensures only numbers that are integers, and within the stated range are included in the modearray varible.
EDIT to include searching for mode (highest occurring number within group)
My approach will do three things to get mode
sort the array,
walk through the sorted array tracking count of the matches along the way.
keep the highest string of matches.
To do this, I will use qsort() and looping in the mode() function.
int mode(int *num, int size) {
int count = 0;
int countKeep=0;
int modenum = -1;
qsort(num, size, sizeof(int), cmpfunc);
//now we have size in ascending order, get count of most occuring
for (int x=1; x<size; x++)
{
if(num[x-1] == num[x])
{
count++;
if(count > countKeep)
{
countKeep = count;
modenum=num[x];
}
else
{
count = 0;
}
}
}
return modenum;
}
Here is the complete code for my approach: (This code will capture the mode of a string of numbers with only one mode. You can modify the looping to determine if the string is multi-modal, or having two equally occuring numbers)
#include <ansi_c.h> //malloc
//#include <stdio.h>//I did not need these others, you might
//#include <string.h>
//#include <math.h>
int ValidateInput(char *num);
int mode(int *num, int size);
int cmpfunc (const void * a, const void * b);
enum {
VALID,
FLOAT,
SMALL,
LARGE
};
int main(int n, char **p)
{
int *modearray, size, i;
int *a;
char number[10];
int status=-1;
int modeOfArray;
printf("What is the size of the Array?");
scanf("%d", &size);
modearray = malloc(size*sizeof(int));
a = malloc(size);
printf("Enter an integer value 1: (1 to 30): ");
for (i=0; i<size; i++)
{
scanf("%s", number);
//Validate Number:
status = ValidateInput(number);
switch(status) {
case VALID:
modearray[i] = atoi(number);
printf("Enter an integer value %d: (1 to 30): ", i+2);
break;
case FLOAT:
printf("float detected, enter an integer");
i--;//try again
break;
case SMALL:
printf("value too small, enter value from 1 to 30");
i--;//try again
break;
case LARGE:
printf("value too large, enter value from 1 to 30");
i--;//try again
break;
default:
//do something else here
break;
}
}
modeOfArray = mode(modearray, size);
getchar();//to view printf before execution exits
}
int ValidateInput(char *num)
{
if(strstr(num, ".")!=NULL) return FLOAT;
if (atoi(num) < 1) return SMALL;
if (atoi(num) > 30) return LARGE;
return VALID;
}
int mode(int *num, int size) {
int count = 0;
int countKeep=0;
int modenum = -1;
qsort(num, size, sizeof(int), cmpfunc);
//now we have size in ascending order, get count of most occuring
for (int x=1; x<size; x++)
{
if(num[x-1] == num[x])
{
count++;
if(count > countKeep)
{
countKeep = count;
modenum=num[x];
}
else
{
count = 0;
}
}
}
return modenum;
}
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
Assuming that the question is about crashing after the scanf in to array:
int main(int n, char **p) {
int *modearray, size, i;
printf("What is the size of the Array?");
scanf("%d", &size);
modearray = malloc(size * sizeof(int)); //imo size of int is 4 so u can replace with
for (i=0; i<modearray[size]; i++) {
printf("Enter an integer value (1 to 30): ");
scanf("%d", modearray[i]);
if (modearray[i] < 1 || modearray[i] > 30) {
printf("Please enter a value within the range");
scanf("%d", &modearray[i])
}
else if (sscanf(p[i], "%i", &a[i]) != 1) {
printf("ERROR\n");
return -1;
}
}
}