C while loop is printing extra number - c

Can someone help me. My code is printing an extra number
It's suppose to work like this:
if is N=38
then it's suppose to print
32.0
33.8
35.6
37.4
but mine prints
32.0
33.8
35.6
37.4
39.2
how do i get rid of the last number. I'm still a beginner so i'm quite bad at this
#include<stdio.h>
int main(){
int i, n;
float f;
printf("toogoo oruulna uu: ");
scanf("%d", &n);
i=0;
while (f<=n){
f = (9.0/5.0 * i) + 32;
printf("%.1f\n", f);
i++;
}
return 0;
}

A quick fix
while (1){
f = (9.0/5.0 * i) + 32;
if(f>n) // Move condition to after calculation
break;
printf("%.1f\n", f);
i++;
}
This will also solve the bug that you're using f before it's initialized.

You can do this:
#include<stdio.h>
int main(){
int i, n;
float f;
printf("toogoo oruulna uu: ");
scanf("%d", &n);
i=0;
f=0;
while (f<=(n-1)){
f = (9.0/5.0 * i) + 32;
printf("%.1f\n", f);
i++;
}
return 0;
}
Look while (f<=(n-1)) , the while loop will stop 1 iteration earlier and make sure you are setting the f variable with a value before you use it!

Related

My 'scanf' loop doesn't stop; while condition is not working

I was supposed to do this exercise: Write a program in C to print a frequency chart on the screen.
Input and output: The program receives as input a sequence of triples (number, frequency, character). For each sequence it should print a slash, producing a graph as in the example below.
Example For input
(5,12, -) (4,17, -) (2,1, -) (1,19, +)
the program should print
5 | ------------ 12
4 | ----------------- 17
2 | -
1 | +++++++++++++++++++ 19
I realize that if I put a space before the sentence in the scanf function, it works very well, but the program desdon't end when it was expected
int main()
{
int x, b, i, u;
char n;
do{
u = scanf(" (%d,%d,%c)", &x, &b, &n);
printf("%d |", x);
for (i = 0; i < b; i++){
printf("%c", n);
}
printf(" %d\n", b);
}while(u == 3);
}
It was expected that, when the scanf don't read the 3 things it was supposed to, the while loop ends and the program is finished. But, when it happens, he still waiting for a new input. How do I fix that?
just check for the returned value of u and then use an if condition. This shold stop the while loop and exit the program
int main()
{
int x, b, i, u;
char n;
do{
u = scanf(" (%d,%d,%c)", &x, &b, &n);
if(u == 3){
printf("%d |", x);
for (i = 0; i < b; i++){
printf("%c", n);
}
printf(" %d\n", b);
}
}while(u == 3);

How do I add a loop for scanf in C?

I have a short question:
How can I expand my program so that it checks if I entered the right format?... if not the program should repeat the scanf.
This is how far I came:
#include <stdio.h>
int main()
{
float zahlen[2];
int i = 0;
while (i < 2 && zahlen != EOF) {
printf("%d. Zahl", i + 1);
scanf_s("%f", &zahlen[i]);
}
printf("Division: %f\n", zahlen[0] / zahlen[1]);
printf("Produkt: %f\n", zahlen[0] * zahlen[1]);
printf("Summe: %f\n", zahlen[0] + zahlen[1]);
printf("Diffenrenz: %f\n", zahlen[0] - zahlen[1]);
printf("Mittelwert: %f\n", (zahlen[0] + zahlen[1]) / 2);
getchar();
return 0;
}
Would appreciate any help of you. Have a nice day/night.
You should define what a right format is. But in a form of pseudo-code
float input;
// First get the input
do {
sacnf_s("%f", &input);
} while (!IsRightFormat(input)); // If the input was not correct get it again
// Do your stuff here
// ...

Why does printf not print anything after my while loop

Here's my code
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int x = 0;
int y = 0;
float a[5][2]; //array
float b[3][2]; //array
float c[2][2]; //array
FILE *fr;
//int c;
float power;
char unit[5];
//int N; //Number of sensors
float TI; //Time interval
//char M; //Midpoint
//char T; //Trapezoid
//int SR; //Sample Rate
fr = fopen("sensor_0.txt","r");
/*fr = fopen("sensor_1.txt","r");
fr = fopen("sensor_2.txt","r");
*/
//----------------------------------------------------------------------------------------------------------------------------
printf("The contents of %s file are :\n", "sensor_0.txt");
while ( !feof( fr ) )
{
fscanf(fr, "%f %f %s",&TI, &power, unit);
//printf("%f, %f \n", TI,power); //print
a[x][y] = TI;
a[x][++y]= power;
x++;
y = 0;
}
fclose(fr);
//----------------------------------------------------------------------------------------------------------------------------
printf("%s", "hello");
return 0;
}
Why isn't my string printing out anything after the while loop?
If I uncomment the same line inside the while loop, it prints properly. I've also tried just adding simple printf("hello") yet nothing seems to work after the while loop.
Edit - minor formatting.
output should just be
700 25.18752608 mW
710 26.83002734 mW
720 26.85955414 mW
730 23.63045233 mW
I suspect the file has 5 lines, not 4.
Your test of !feof() fails because you have not hit the end of file yet when you try to read the 6th line. fscanf fails but you do not test the return value. So you store TI and power beyond the end of the 2D array, invoking undefined behavior.
Changing the loading code this way should fix the problem:
while (x < 5 && fscanf(fr, "%f %f %4s", &TI, &power, unit) == 3) {
a[x][0] = TI;
a[x][1] = power;
x++;
}
if (x != 5) {
printf("incomplete input\n");
}
Doing what chqrlie suggested worked.
"instead of while ( !feof( fr ) ) that is incorrect, use while (fscanf(fr, "%f %f %4s",&TI, &power, unit) == 3)"

How to make compiler repeat until the number 0 is presed

I'm wondering how to make the compiler repeat itself if the user presses a random button at the end. But if the user presses "0" the compiler exits.
My code:
#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <float.h>
struct mystruct
{
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
struct mystruct data;
float max = 0;
float min = FLT_MAX;
float sum = 0;
float avg = 0;
int i = 0;
float resultat = 0;
printf("Startnummer: \n");
scanf_s("%f", &data.startnummer);
printf("Hoppnummer:\n");
scanf_s("%f", &data.hoppnummer);
printf("Svarighetsgrad:\n");
scanf_s("%f", &data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("domarpoang %d\n", i + 1);
float f;
if (scanf_s("%f", &f) == 1)
{
if (f < min) min = f;
if (f > max) max = f;
data.domarpoangs[i] = f;
}
else
{
printf("error parsing float\n");
exit(0);
}
}
system("cls");
printf("Startnummer: %.1f \n", data.startnummer);
printf("Hoppnummer: %.1f\n", data.hoppnummer);
printf("Svarighetsgrad: %.1f\n", data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("Domarpoang %d: %.1f\n", (i + 1), data.domarpoangs[i]);
}
for (i = 0; i < 7; i++)
{
sum += data.domarpoangs[i];
}
sum = sum - (max + min);
avg = sum/5;
resultat = avg * 3 * data.svarighetsgrad;
printf("Hoppoang:%.2f \n", resultat);
printf("Tryck tangent for nytt hopp!");
getchar();
getchar();
return 0;
}
*If the user presses random button, the compiler repeat itself from the beginning
*If the user presses 0, the compiler exits.
Any help is appreciated, thank you.
This answer puts a loop around the body of your main() code, taking care to re-initialise some of the variables for the next iteration.
There are many SO questions about getting keyboard input and clearing the debris. I know of no simple standard ways of testing for keyboard input such as kbhit(), for taking a single key input such as getch() or for flushing the input. Even getchar() is horrible - it won't return until you have pressed "Enter" which it leaves in the input buffer. This has resulted in many SO answers with impenetrable (to me) formats for scanf() to flush the input, or testing if (getchar() == EOF) - which does not respond to the "Enter" key.
So I have put a simple wrapper around the main() code, which terminates when '0' is entered followed by a control char (because fgets() appends the newline) or terminator. This removes the need to clean up the input - except in the case where the user inputs some silly typing. GIGO!
#include <stdio.h>
#include <float.h>
#define BUFFSIZE 10
struct mystruct {
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
char kbuff [BUFFSIZE+1];
struct mystruct data;
float max;
float min;
float sum;
float avg;
int i;
float resultat;
do {
max = 0; // initialise for each loop
min = FLT_MAX;
sum = 0;
printf ("Body of your main loop\n");
fgets(kbuff, BUFFSIZE, stdin);
} while (kbuff[0] != '0' || kbuff[1] >= ' ');
return 0;
}

C scanf in loop continues automaticly without input

I'm trying to get input in an array, I expect input like the following.
5 (Number of the second dimensions in the array)
2 (Number of the first dimensions in the array)
So we get an array deeln[2][5] in this example. I try to get it with the following code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
scanf("%s", temp);
for(cj = 0; cj < k; cj++){
deeln[ci][cj] = temp[cj*2]-'0';
}
}
//loop while.
}
But i've got a problem, whenever i try to input, the program runs automaticly without getting any input when it loops around the third scanf for the 2nd or 3rd time. So then i'm not able to input anything.
What to do? Has it something to do with pointers or am i using scanf wrong?
UPDATE:
If I enter a printf after printf("cj is nu %i \n", cj); then the output also just came after the loop was going its own way. and not before i should give more input, using the third scanf.
The solution of my question was quite easy. I found it after thinking of my input. The problem was that in the input, as described, there were spaces. Somehow scanf can't handle with spaces, unless you use some other syntax. But my solution is to just use fgets instead of scanf where I wanted to get the input. So the new and working code is as follows:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp = 0;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0;
//get input
scanf("%i", &k);
scanf("%i", &d);
char temp[20];
int deeln[d][k];
memset(deeln, 0 , sizeof(deeln));
memset(temp, 0 , sizeof(temp));
for(ci = 0; ci < d; ci++){
fgets(temp, 20, stdin);
for(cj = 0; cj < k; cj++){
ta = cj*2;
deeln[ci][cj] = temp[ta]-'0';
}
}
//loop while.
return 1;
}
Thanks for helping everbody, even though we all didn't came to this. But I hope it will help others!
Two places to look:
1)
cj = 0;//initialize cj before using here
scanf("%i", &temp[cj]);//temp is both an array, and an int. Fix your format specifier,
//and use an index operator - temp[?] (not sure I am using the right index)
2)
deeln[ci][cj] = temp[cj*2]-'0'; //fix your logic here (array index will be exceeded)
An example of working code...
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
for(cj = 0; cj < k; cj++){
if(scanf("%i", &temp[cj]) != EOF)
{
deeln[ci][cj] = temp[cj]-'0';
}
else deeln[ci][cj] = -1;
}
}
getchar();
//loop while.
}
you can play with the index of temp[cj] to make it what you actually want, but I assume you are intending to read from stdin, then populate deeln[][] with that value, for each scanf.
If you want to parse a string containing spaces and digets, "1 3 8 5 3", you could use strtok()
But your code as it is is not reading a string in, it is reading integers.
This is not perfect, you will have to do some debug, but will illustrate strtok(). You have to enter spaces between each digit after indices are selected: i.e.:
3
3
4 6 8
2 4 7
1 2 8
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
char inStr[d][k*5]; //space for up to k 3 digit numbers with 1 space each
char *buf=0;
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
if(scanf("%s ", inStr[ci]) != EOF)
{
buf = strtok(inStr[ci], " ");
cj = 0;
while(buf && (cj < k))
{
deeln[ci][cj] = atoi(buf);
cj++;
}
}
}
//getchar();waits for user input, pauses execution
}

Resources