I want to read a .dat file whose first line consists of a float and all consecutive lines are "int * int" or "int / int" and print or return whether the float is a result each division or multiplication.
I am very unpleased with the results that I am getting. My experience is limited to only a couple of hours doing C. Therefore I have no idea what is missing for the program to do what the code is looking like it would do.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int countlines(FILE* f){
int nLines = -1;
char xLine[10];
while(fgets(xLine,10,f)!=NULL){
nLines+=1;
}
return nLines;
}
int main(){
FILE * fPointer = fopen("test.dat", "r");
float dpFloat;
char oprnd[10];
int frstInt;
int scndInt;
//get float from first line
fscanf(fPointer, "%f", &dpFloat);
//count amount of lines below float
int amtLines = countlines(fPointer);
//loop through the other lines and get
int i;
for (i = 0; i < amtLines; i++){
fscanf(fPointer, "%d %s %d", &frstInt, oprnd, &scndInt);
//checking what has been read
printf("%d. %d %s %d\n", i, frstInt, oprnd, scndInt);
//print 1 if firstline float is quot/prod of consecutive line/s
//else 0
if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);
}
fclose(fPointer);
return 0;
}
Problem 1: strcmp returns 0 when its arguments are equal, not 1.
Problem 2: frstInt/scndInt will truncate the result. Fix it by adding 1.0* to the expression.
The lines
if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);
need to be
if (strcmp(oprnd,"*") == 0) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") == 0) printf("%i\n", (1.0*frstInt/scndInt)==dpFloat);
// ^^^ ^^^
Please be aware of the pitfalls of comparing floating point numbers. It's best to compare them within a tolerance. See Comparing floating point numbers in C for some helpful tips.
Related
PROBLEM: Create a loop that, for a positive integer n, finds the biggest integer k for which n ≥ 2k. (We are essentially finding the integer log base-2 of n.) Do not use pow, log2, or any functions from math.h to implement this!
Last printf statement doesn't work.
My solution:
#include <stdio.h>
int main(void){
int k=1, n, j=2;
printf("Enter positive number: ");
scanf("%d", &n);
while(n>=j*k){
k++;
}
printf("k: %d", k);
return 0;
}
It works,
beside the result is incorrect, you may want to print the k-1 value.
Reason you are not seeing it may depend on missing "\n" at the end of printf() which do not refresh the output buffer
In addition to #Jack's (correct) answer, you might consider a different solution to the problem: use bit shifting operations. Given the problem asks for log base 2, one can count the number of "shift right" operations that are required to make n zero.
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int k = -1;
unsigned long int n;
if (argc != 2) {
fprintf(stderr, "usage: %s n\n", argv[0]);
return 1;
}
n = strtoul(argv[1], NULL, 0);
while (n) {
k++;
// Shift the bits in n to the right by one place. Equivalent to n /= 2.
n >>= 1;
}
printf("%d\n", k);
return 0;
}
I am having difficulties initializing an array to how values given from a for loop, I want to discard the prime numbers calculated and then keep the non prime numbers in an array, which the size of the array must be unknown from the beginning. I must then call collect the numbers from the array and then apply the Carmichael equation to them to find Carmichael numbers.
Applying the equation to the values in the array is what I am finding difficult as well.
This is my code:
int main(int argc, char **argv){
int a ,b;
int notPrime[] = {};
printf("Type in two non negative intergers: \n");
scanf("%d" "%d", &a , &b);
int i=a , k=0 ,count=0, j, p, m;
for (i < b;){ //from the integers given b must be the larger of the two
if (i==0 || i==1) { //to calculte the prime numbers
notPrime[k]=i;
}else{
for( j=2;j<i;j++){
if(i%j==0){
break;
}else{
notPrime[k]=i;
}
}
}
i++;
k++;
}
p=0;
if (p<=k){
for (m=1;m<notPrime[p];m++){
if((pow(m,notPrime[p])-m)%notPrime[p]==0){ //use of the values in the array and use of the carmichael equation
count=count+1;
}
if(count==notPrime[p]-1){
Printf( "%d \n", ¬Prime[p]) ;
}
}
}
return 0;
}
i have errors on for (i < b;){, if((pow(m,notPrime[p])-m)%notPrime[p]==0){ and finally the print statment Printf( "%d \n", ¬Prime[p])
Please could I get a little help, just set me in the right direction and I will try to correct.
xRapture
for (i < b;){
This is not a valid syntax for for loop . You can write like this instead -
for (;i < b;){
And this -
if((pow(m,notPrime[p])-m)%notPrime[p]==0){ //
pow return double and notPrime[p] is int . % operator on double and int .
Explicitly cast result of pow to int.
Also this -
printf( "%d \n", ¬Prime[p]) ;
^ this is not needed
don't pass address of int.
Edit -
You can declare your array as this after taking input a and b -
int notPrime[a] = {0}; // or size b as you desire
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr §6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}
matthewmpp#annrogers:~/Programming/C.progs/Personal$ cat prime4.c
/*
* File: main.c
* Author: matthewmpp
*
* Created on November 7, 2010, 2:16 PM
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
/*
prime numbers.
version4
should tell whether a number is prime or not prime.
by using other prime numbers.
*/
int input_func ()
{
char line[100];
int n_input;
while (1) {
printf("Please enter a whole number.\n");
fgets(line, sizeof (line), stdin);
sscanf(line, "%d", &n_input);
if (n_input >= 0)
break;
return (n_input);
}
}
int ifstatements_func (n_ifstate)
int n_ifstate;
{
if (n_ifstate == 0) {
printf("The number, %d, is not prime and has no factors.\n", n_ifstate);
exit(1);
}
if (n_ifstate == 1) {
printf("The number, %d, is not prime.\n", n_ifstate);
printf("The factors of %d, is %d.\n", n_ifstate, n_ifstate);
exit(1);
}
if (n_ifstate == 2) {
printf("The number, %d, is a prime.\n", n_ifstate);
printf("The factors of %d, are 1 and %d.\n", n_ifstate, n_ifstate);
exit(1);
}
if (n_ifstate == 3) {
printf("The number, %d, is a prime.\n", n_ifstate);
printf("The factors of %d, are 1 and %d.\n", n_ifstate, n_ifstate);
exit(1);
}
return (n_ifstate);
}
int square_root_func (n_prmfnc)
int n_prmfnc;
{
int i; //counter
float sq_root_f;
int sq_root_i;
int primes[100];
int length_primes;
primes[0] = 2; /*first prime is 2.*/
primes[1] = 3; /*second prime is 3.*/
length_primes = sizeof (primes);
//printf ("before.sq_root.value of n_prmfnc=%d\n", n_prmfnc);
sq_root_f = sqrt(n_prmfnc);
sq_root_i = sq_root_f;
//printf ("prmfnc.after.sq_root\n");
//printf ("value of sq_root=%.3f\n", sq_root_f);
//printf ("value of sq_root=%d\n", sq_root_i);
return (sq_root_i);
}
int prime_func (sq_root_pf, n_pf)
int sq_root_pf, n_pf;
{
int prime_counter;
int prime_temp;
int prime_flag=0;
int primes_pf[100];
int i; //counter
primes_pf[0]=2;
primes_pf[1]=3;
primes_pf[2]=5;
printf ("before.for.in.pf");
for (i = 0; i <= 100; ++i) {
printf ("after.for.in.pf");
if (primes_pf[i] <= sq_root_pf) {
printf ("before.modulus.in.pf");
prime_temp = n_pf % primes_pf[i];
printf ("after.modulus.in.pf");
if (prime_temp == 0) {
++prime_counter;
if (prime_counter == 0)
prime_flag = 1; /*yes, number is prime.*/
}
}
}
return (prime_flag);
}
int main() {
int n_main1; //number from input
int n_main2; //number after if statements
int sq_root_main; //square root of number from function
int prime_flag_main; //value of 1 if it is a prime
n_main1 = input_func ();
printf("main.after.input.function=%d.\n", n_main1);
n_main2 = ifstatements_func (n_main1);
printf ("main.after.ifstatments.function=%d\n", n_main2);
sq_root_main = square_root_func (n_main2);
printf ("main.after.square_root_func_func=%d\n", sq_root_main);
prime_flag_main = prime_func (sq_root_main, n_main2);
printf ("main.after.prime_func=%d\n", prime_flag_main);
return (EXIT_SUCCESS);
}
OUTPUT:
matthewmpp#annrogers:~/Programming/C.progs/Personal$ cc -c prime4.c
matthewmpp#annrogers:~/Programming/C.progs/Personal$ cc -o prime4 prime4.c -lm
matthewmpp#annrogers:~/Programming/C.progs/Personal$ ./prime4
Please enter a whole number.
44
main.after.input.function=44.
main.after.ifstatments.function=44
main.after.square_root_func_func=6
Floating point exception
matthewmpp#annrogers:~/Programming/C.progs/Personal$
STATEMENT: the error is in the prime_func. I believe the cause is the modulus (% sign).
QUESTION: why am I getting the Floating Point Exception and how do I fix it?
What happens is a division by zero. You only initialise the first three entries of primes_pf, but iterate over all of them (actually, your loop runs even one past the last entry; use i < 100 instead of i <= 100 to fix this). For all but the first three entries, you divide by some unitialised quantity, and one of the entries apparently happens to be zero. Don't use unitialised values.
"Floating point exception" is a misnomer. It only happens on integer division by zero and a few other division-related operations.
Not sure I believe the answer above!
X = 5.0;
Y = 0.0;
Z = X/Y;
This will give a floating point exception....
The problem would appear to be that prime_pf is only initialised for 3 elements. So the modulo is attempting to divide by zero.
BTW, if you add \n to your printf statement, and add the extra statement
fflush(stdout);
you are more likely to see the debug output before the program errors.
The problem exists in your primes_pf variable. You seemed to have initialized the first three elements of this integer array, but when iterator i goes beyond 2, primes_pf[i] is reading from uninitialized memory and getting compared to sq_root_pf; that can't be right.
I haven't taken the time to fully understand your algorithm but my best guess is that you forgot to assign a new value to primes_pf somewhere in your for loop.
sqrt(x) needs x to be of type double, you have used int.
Cast to double (double)n_prmfnc
I am VERY sure about this !