Converting a signed char to an int in c [closed] - c

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 4 years ago.
Improve this question
Im having an issue converting a signed string into an int.
char *crn1, *crn2, *credit1, credit2;
char course1, course2;
crn1=strtok(course1,"/");
credit1=strtok(NULL,"/");
crn2 = strtok(course2,"/");
credit2 = strtok(NULL,"/");
Im trying to convert the signed char credit1 or credit2 to an integer for math used later on in my code. I either get a huge number or an error.

Use strtol (which is the safer version of atoi).
#include <stdlib.h>
#include <stdio.h>
int main() {
char *str = "5";
int n;
n = strtol(str, NULL, 10);
printf("n+1 is %d\n", n+1);
}
Using atoi:
#include <stdlib.h>
#include <stdio.h>
int main() {
char *str = "1";
int n;
n = atoi(str);
printf("n+1 is %d\n", n+1);
}
If instead of converting the digits in the string into an integer, you'd rather use the numerical value of the character, you can:
#include <stdio.h>
int main() {
char c = 'a';
printf("ascii code of %c is %hhu\n", c, c);
printf("after %c is %c with ascii code %u", c, c+1, c+1);
return 0;
}

Related

Sum of series in c language [closed]

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 1 year ago.
Improve this question
Sum of series using c language
sample input : 12 15
sample output : 54
sample input : 1 100
sample output : 5050
#include <stdio.h>
int main(){
int a, b;
scanf("%d %d", &a, &b);
printf("%lld",a*(b+1)/2);
return 0;
}
Your formula: a*(b+1)/2 is wrong
For a + (a+1) + (a+2) + ... + (b-1) + b use the formula:
((b+1)*b - a*(a-1))/2 or (b-a+1)(b+a)/2
(assuming that b >= a)
So the program could be:
#include <stdio.h>
int main(void)
{
int a, b;
if (scanf("%d %d", &a, &b) != 2) exit(1);
if (b < a) exit(1);
printf("%d", ((b+1)*b - a*(a-1))/2);
return 0;
}
The %lld format specifier is used to print a long long int. The argument you're passing has type int. Mismatching format specifiers triggers undefined behavior, which in this case will likely result in output you don't expect.
To print an int use %d.
printf("%d",a*(b+1)/2);

How to convert a position of a pointer to int in c [closed]

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 1 year ago.
Improve this question
#include <stdio.h>
int main()
{
char* s = "123456";
int number = atoi(s[0]);
printf("test %d",number);
return 0;
}
I want it to print just the first character of my string as an integer, so I can use it in another algorithm. What is the most efficient way to do it?
s[0] is already a signed char you can print it right away
printf("test %d", s[0]); // test 49
or
int number = s[0];
printf("test %d", number); // test 49
printf("test %d, %d, %d", s[0], s[1], s[2]); // test 49, 50, 51
printf("test %c, %c", number, s[1]); // test 1, 2

convert string to double , the answer is correct ,but not very accurate [closed]

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 2 years ago.
Improve this question
I want to use atof to convert my string to a double,the answer is correct ,but not very accurate
ATTENTION: because of some other reasons, fscanf is not permitted
my code is :
#include <stdio.h>
#include <stdlib.h>
#define MAXCN 50
int main(void)
{ FILE* lstm_txt = NULL;
char lstm_weight[MAXCN] = {0};
int lstm = 0;
int i = 0;
float lstm_val;
if ((lstm_txt = fopen("test1.txt", "r"))== NULL){
fprintf(stderr,"error:file open failed 'test1.txt'.\n");
return 1;
}
while ((i + 1 < MAXCN) && ((lstm = fgetc(lstm_txt)) != ' ' ) && (lstm != EOF)){
lstm_weight[i++] = lstm;
}
//lstm_weight[i] = 0;
printf("\n lstm_weight: %s\n\n", lstm_weight);
lstm_val = atof(lstm_weight);
printf("\n convert \"lstm_weight\" to lstm_val is : %f\n\n", lstm_val);
return 0;
}
my file : lstm_txt is :
4.217959344387054443e-01 -2.566376626491546631e-01 2.173236161470413208e-01 4.217959344387054443e-01
code hasn't bug, and the result is :
lstm_weight: 4.217959344387054443e-01
convert "lstm_weight" to lstm_val is : 0.421796
but I want Istm_val is 0.4217959344387054443 ,how can I do that?
you could try something like sprintf()
here's an example:
#include <stdio.h>
int main() {
char str[50];
double n = 0.3984092590879;
sprintf(str, "%lf", n);
printf(str);
return 0;
}
prints out:
0.3984092590879
Printing %.17f you can have a precision up to 0.42179593443870544
printf("\n convert \"lstm_weight\" to lstm_val is : %.17f\n\n", lstm_val);
A double typically has about 15 digits of decimal precision. You will not get more accuracy than that if you store the value in a double. You are getting less because you didn't tell printf how many digits of precision to use for output, so you got the default.
Use something like %0.15f instead of %f.
convert "lstm_weight" to lstm_val is : 0.421795934438705
With %0.20f, I get:
convert "lstm_weight" to lstm_val is : 0.42179593443870544434
That's the best you'll do with a double.

How to print the number of digits of a number that is entered by the user in C? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hello I am trying to write C code that prompts the user for a positive integer and then prints out the number of digits in that number. Assuming that the user enters a positive integer, no error checking is needed.
My problem is after 'ctrl-d' is pressed the output is always:
"# of digits = 1"
If the user types 1023 the program should print:
"# of digits = 4"
I am new to C and am trying to get a feel for how scanf works. Thank you!
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int count = 0;
char n;
printf("Enter positive int!\n");
while(scanf("%c",&n) != EOF);
{
count++;
}
printf("# of digits = %d\n", count);
return 0;
}
You may use %d format specifier enter an decimal integer with scanf, then apply following function:
int getNumOfDigits(int num, int base /*= 10*/)
{
int count = 0;
if (num < 0) {
num = -num;
}
while (num > 0) {
count++;
num /= base;
}
return count;
}
It is untested, but general idea is to divide by ten, then you go with number of digits of an int number:
printf("# of digits = %d\n", getNumOfDigits(number, 10));
Note that you should also check returned value from scanf for error handling (when number is not in correct format). For instance:
if (scanf("%d", &number) != 1) {
printf("Incorrent input for decimal number!\n");
exit(EXIT_FAILURE);
}
You could simply read in a string and then use strlen() to check its length:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_LEN 64
int
main(int argc, char** argv)
{
char buf[MAX_LEN] = {0};
scanf("%s", buf);
fprintf(stdout, "string length: %lu\n", strlen(buf));
return EXIT_SUCCESS;
}
If you need to validate the input (i.e., to ensure it is a number), you could read in the string as above, and before printing the string length, loop over each character and use isdigit() to test if that character is an integer. If it isn't, then the input is either a negative number or some other non-numerical character.
Here is one way to find the number of digits by using log10()
#include <stdio.h>
#include <math.h>
int main (void)
{
unsigned number;
scanf("%u", &number);
printf("%.0f\n", ceil(log10((double)number+1)));
return 0;
}
And here is another way, sprintf() returns the number of characters written
#include <stdio.h>
#include <math.h>
int main (void)
{
unsigned number;
char str[20];
scanf("%u", &number);
printf("%d\n", sprintf(str,"%u", number));
return 0;
}

Array doesn't get calculated [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Good day , i'm having this issue with the following C code . I'm trying to perform this operation, the sum of (each entered number has to be multiplied by its generated one) . What am I missing ?
i'm getting this error : incompatible types when assigning to type 'float *' from type 'float' .
Any help will be welcomed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <math.h>
int main(int argc, char *argv[])
{
application();
return 0;
}
void application(void)
{
int input = 0;
float number[10];
float total =0;
float *ptr;
float generatedNum;
srand(time(NULL));
for(input; input<11; input++)
{
generatedNum = 2 *(float)rand()/(float)RAND_MAX - 1;
printf("\n\n\t\tEnter number %d : ", input);
scanf("%f", &number[input]);
ptr = number * generatedNum;
printf("\n\t\t\t\t\tMachine Value: %.1f", generatedNum);
}
for(input; input<11; input++)
{
total += *ptr;
ptr++;
}
printf("\n\n\n\t\tTHE NEURON IS: %.2f", total);
}
An easier solution is to simply keep everything in one loop. There really isn't a need for a pointer in this situation as nothing requires them, add the values as you get them. Also you never use the generatedNum (although maybe this is for further development??)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void application(void)
{
int input = 0;
float number[10];
float total =0;
float generatedNum;
srand(time(NULL));
for(; input<10; input++)
{
generatedNum = 2 *(float)rand()/(float)RAND_MAX - 1;
printf("\n\n\t\tEnter number %d : ", input);
scanf("%f", &number[input]);
total += number[input];
printf("\n\t\t\t\t\tMachine Value: %.1f", generatedNum);
}
printf("\n\n\n\t\tTHE NEURON IS: %.2f", total);
return;
}
int main(int argc, char *argv[])
{
application();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void application(void)
{
int input = 0;
float number[10];
float total =0;
float *ptr;
float generatedNum;
srand(time(NULL));
for(; input<10; input++)
{
generatedNum = 2 *(float)rand()/(float)RAND_MAX - 1;
printf("\n\n\t\tEnter number %d : ", input);
scanf("%f", &number[input]);
ptr = number;
printf("\n\t\t\t\t\tMachine Value: %.1f", generatedNum);
}
for(input = 0; input<10; input++)
{
total += *ptr;
ptr++;
}
printf("\n\n\n\t\tTHE NEURON IS: %.2f", total);
}
int main(int argc, char *argv[])
{
application();
return 0;
}
your array will get out of bound if you go for < 11 because it might contain 10 position but it's starting at 0.
Also the first loop manipulates your input variable which is then higher than the required condition of your second loop.
So you need to set it back to 0.
Working example!

Resources