Folks, I'm trying to use an 'if' statement with a char variable, but it doesn't seem to notice when the 'yes' condition is met. I don't know if there's a way to do this without the array. Here's my code below. Any help is much appreciated.
// Running times calculator
# include <iostream>
# include <math.h>
using namespace std;
int main ()
{
float cTime;
float gTime;
float cDist;
float gDist;
float min;
float sec;
float cMin;
float cSec;
float p1000;
char response[1];
int blank;
printf ("Welcome to the running times calculator.\n\nEnter your completed race distance in metres: \n");
scanf ("%f", &cDist);
printf("Enter your completed race time. Type minutes, hit enter. Type seconds, hit enter\n");
scanf ("%f" "%f", &cMin, &cSec);
cTime = cSec+(60*cMin);
p1000 = pow(1000/cDist,1.1)*cTime;
printf ("Would you like to enter another race time to improve prediction accuracy? \n");
scanf ("%s", &response);
if(response == "yes")
{
printf ("Enter your completed race distance in metres: \n");
scanf ("%f", &cDist);
printf("Enter your completed race time. Type minutes, hit enter. Type seconds, hit enter\n");
scanf ("%f" "%f", &cMin, &cSec);
cTime = cSec+(60*cMin);
p1000 = ((pow(1000/cDist,1.1)*cTime)+p1000)/2;
}
printf ("What is your goal race distance in metres? \n");
scanf ("%f", &gDist);
gTime = pow(gDist/1000, 1.1)*p1000;
min = gTime/60;
sec = remainder(gTime,60);
if (sec < 0)
{
sec = sec + 60;
min = min - 1;
}
printf ("Your predicted time for a race of %.0f metres is %.0f minutes and %.0f seconds", gDist, min, sec);
scanf("%f", &blank);
return 0;
}
You got a few problems with the way you treat your char array.
char response[1]; You create an char array that consists of one character here but then you treat it as a string in these lines:
scanf ("%s", &response);
if(response == "yes")
also note that you can't simply compare a char array and a string literal with == all you'd do would be comparing addresses. You'd either have to use strcmp() or better use std::string.
Didn't check all the code, but you use an
operator ==
that doesn't work with a char [], it's for string
use strcmp instead.
Related
I wanted to write a little calculator, which I have already done by using cout and cin, and I used double instead of int to not only get integers as an output.
At school, I then saw that we're going to use printf() and scanf(). To practice the new commands, I wanted to rewrite my program, but when I run my program I only see a lot of zeros after the comma as an output. Does anybody know why?
I wanted to rebuild a calculator with double instead of int to not only get integers as a result.
This is the code:
#include <stdio.h>
using namespace std;
int main(){
printf ("Taschenrechner\n\n");
int zahl1, zahl2;
char rechop;
double erg;
printf ("Gib die Rechnung ein: ");
scanf ("%d", &zahl1);
scanf ("%c", &rechop);
scanf ("%d", &zahl2);
if (rechop == '+'){
erg = zahl1+ zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '-'){
erg = zahl1 - zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '*'){
erg = zahl1 * zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else if (rechop == '/'){
erg = zahl1 / zahl2;
printf ("Ergebnis: ");
printf ("%f", erg);
}
else {
printf ("Keine gültige Rechenoperation!");
}
return 0;
}
To decide how many decimal numbers show, you can use %.2f (where ".2" stands for "2 decimals after the comma") in the printf instead of simply %f.
Edit: forgot to say that, by doing that, your result get rounded (and not simply "cut").
There is your code updated (and translated):
#include <stdio.h>
using namespace std;
int main(){
printf ("Calculator\n\n");
int num1, num2;
char simbol;
double res;
printf ("Insert the expression: ");
scanf ("%d", &num1);
scanf ("%c", &simbol);
scanf ("%d", &num2);
if (simbol == '+'){
res = num1+ num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '-'){
res = num1 - num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '*'){
res = num1 * num2;
printf ("Result : ");
printf ("%.2f", res);
}
else if (simbol == '/'){
res = num1 / num2;
printf ("Result : ");
printf ("%.2f", res);
}
else {
printf ("Not a valid expression!");
}
return 0;
}
Your output has zeros after the decimal point, because that's actually what is in the variable (erg) that you are printing.
Your problem is that this line uses integer division:
erg = zahl1 / zahl2;
When the compiler is picking which operation to do, it only looks at the data type of the inputs (which are both int). The result is then converted to be stored into erg, but that doesn't affect the division behavior chosen.
Change the line to:
erg = zahl1 * 1.0 / zahl2;
or
erg = zahl1;
erg /= zahl2;
so that one of the inputs will be type double, and integer division will no longer be involved.
The problem is that you’re doing operations between int (num1 and num2 are declared as int). In order to have decimal numbers you must do operations between float (or double as in your case).
You can declare num1 and num2 as double directly (and change %d to %lf in the scanf and printf).
Another possibility is to do an explicit type cast: type cast is basically a conversion from a type to another and it is explicit because you’re writing it instead of letting the compiler do it for u (in your og program a cast is done by the compiler, after the operation, to fit the int result in the double type variable erg).
So an example is:
result = num1 + num2;
Becomes:
result = (double)num1 + (double)num2;
When a friend of mine asked me to debug the problem with a console game project I had found a weird conversion of fprintf in C that I can't figure out. The project was required to keep track of all the information, including scores and update time to a .txt file using C.
-Initialization
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
.
.
.
// in main
time_t timer;
time (&timer);
int num=0,c;
scanf(" %s %ld", inputname,c);
fscanf(fp, "%d", &num);
num++;
char **name;
long *times;
ull *score;
name = new char *[num];
for(int i=0; i<num; i++){
name[i] = new char[MAX];
}
times = new long [num];
score = new ull[num];
//new data
name[num-1] = inputname;
score[num-1] = c;
times[num-1] = timer;
-The I/O parts
.
.
.
// input from file after dynamic variables have fix size
for(int i=0; i<num-1; i++){
fscanf(fp, " %s%d", name[i], &score[i]);
fscanf(fp, "%ld", ×[i]);
}
fseek(fp , 0 , SEEK_SET);
fprintf(fp, "%d\n", num);
//print back to fp
for(int i=0; i<num; i++){
fprintf(fp, "%s %ld ",name[i], score[i]);
fprintf(fp, "%ld\n",times[i]);
}
Problem. if I change
fprintf(fp, "%s %ld ",name[i], score[i]);
fprintf(fp, "%ld\n",times[i]);
to one-line
fprintf(fp, "%s %ld %ld\n",name[i], score[i],times[i]);
the output file will have
NAME1 SCORE1 TIMEINLONG1
NAME2 SCORE2 0
NAME3 SCORE3 0
.
.
.
instead of
NAME1 SCORE1 TIMEINLONG1
NAME2 SCORE2 TIMEINLONG2
.
.
.
After some trying, I found that by reversing the order of scores and times
fprintf(fp, "%s %ld %ld\n",name[i], times[i],score[i]);
I have a correct output
NAME1 TIMEINLONG1 SCORE1
.
.
.
again.
So, how exactly does C do with output stream. I thought the compiler collect the argument in "..." to assemble a string, then flush it to outputstream. Obviously it ignored the time[i] after the first (time[0]).
Is it the problem of the way I intialize times[]?
Or is it the problem with fprintf()?
Apology for such a lengthy page, but I'm really confused about the fprint now.
Solved
edit title from "fprintf with dynamic memory" to "long long int don't take long int well, vise versa."
The problem was not on the dynamic memory things(Sorry I didn't know), but was the type that I used to get and put data in printf, fprintf, scanf, fscanf. According to #Adrian Mole , the mismatch assign long int to a long long int type variables was undefined behavior, and the following I/O action will not be correctly done. It seems that even long long int have more space than those of long long, it is not compatible.
No
long long int c;
scanf("%d",&c);
printf("%d",c);
//or
scanf("%ld",&c);
printf("%ld",c);
Yes
long long int c;
scanf("%lld",&c);
printf("%lld",c);
You have here a classic example of "undefined behaviour!" The variable that is score[i] is (assuming a reasonable definition of the type ull) an unsigned long long int (possibly/probably 64-bits) but both the scanf and 'offending' printf calls use the %ld format specifier (possibly/probably referring to a 32-bit variable).
When printf is called with a "mismatch" between the format specifier and the given argument, you are in undefined behaviour territory!
Fix the issue by specifying the %llu format for the corresponding score[i] argument! For example, in place of:
fprintf(fp, "%s %ld %ld\n",name[i], score[i],times[i]);
use:
fprintf(fp, "%s %llu %ld\n", name[i], score[i], times[i]);
// score[i] is ull ^ | ^ OK - times[i] is (signed) long!
Feel free to ask for further clarification and/or explanation.
The problems start at the following lines:
int num=0,c;
scanf(" %s %ld", inputname, c);
First, you should write &c instead of c as the last parameter. Since scanf writes into its parameters, it should receive addresses of parameters (except strings, I am too lazy to explain why).
Second, since c is int, you need %d, not %ld. Be careful with sizes.
As for your fprintf - again, be careful with sizes. Since score is ull*, and I assume that ull means unsigned long long, you need to print it with %llu format, not %ld. (Note - Andrian Mole also pointed this piece, and posted his answer slightly before I posted mine.)
Another error is:
name[num-1] = inputname;
That reassigns the pointer to heap allocated memory and causes a memory leak. inputname array should be copied into name[n] array, e.g.,
snprintf(name[num-1], MAX, "%s", inputname);
scanf %s may overflow its destination array argument, unless you hard-code the destination size, e.g.:
#define MAX 256
int num=0,c;
char inputname[MAX];
scanf("%256s %d", inputname, c);
Why does this code not work? My IDE is Visual Studio 2013.
#include <stdio.h>
float tempatureGuide(float F, float C);
#define FREEZING_PT 32.0f
#define SCALE_FACTOR (5.0f/9.0f)
int main(void)
{
float fahrenheit = 0.0;
float celsius = 0.0 ;
int convertTemp;
printf ("Enter 0 to calculate Celsius or 1 to calculate Fahrenheit: ");
scanf ("%d", &convertTemp);
if (convertTemp == 0)
{
// compute Celsius
printf("Enter Fahrenheit temperture: ");
scanf("%f", &fahrenheit);
celsius = ((fahrenheit - FREEZING_PT) * SCALE_FACTOR);
printf("Fahrenheit = %f and Celsius = %f\n", fahrenheit, celsius);
float tempatureGuide(fahrenheit, celsius); // Error here
}
else
{
// compute fahrenheit
printf("Enter the temperature in degrees fahrenheit\n\n");
scanf("%f", &fahrenheit);
celsius = (SCALE_FACTOR)* (fahrenheit - FREEZING_PT);
printf("The converted temperature is %f", celsius);
float tempatureGuide(fahrenheit, celsius); // and here
}
return (0);
}
float tempatureGuide(float F, float C){
if (F < 32 || C < 0)
printf("It is freezing!");
else if (F <= 60 || C <= 16)
printf("It is cold");
else if (F >= 70 || C >= 21)
printf("It is just right");
else if (F >= 82 || C >= 28)
printf("It is warm");
else if (F > 95 || C > 35)
printf("It is hot");
else
printf("Please enter a number!");
return (0);
}
The goal here is to add to the converting temperature project I did earlier and add an if else statement function to it that comments on the temp. The error I get is
Error 3 error C2078: too many initializes
on both the lines where I call my function. I searched for an answer but couldn't find any.
This line looks like an attempt at a C++ initialization of a float with one too many arguments (hence the "too many initializers" error), not like a function call.
float tempatureGuide(fahrenheit, celsius);
Presumably you want to call the function and store the result in a variable:
float temp = tempatureGuide(fahrenheit, celsius);
Or just call the function and ignore the return value:
tempatureGuide(fahrenheit, celsius);
Especially since your function always returns 0, so one might question the need for a non-void return type.
You need to call a function
float tempatureGuide(float fahrenheit, float celsius) { //...}
as
float retval = tempatureGuide(fahrenheit, celsius);
or least
tempatureGuide(fahrenheit, celsius); // not need to use return value
Only.
That is just a simple error. Please change 2 lines of code where you are calling tempatureGuide(fahrenheit, celsius); function as follows.
float tempatureGuide(fahrenheit, celsius); --> float ret = tempatureGuide(fahrenheit, celsius);
I tested the same in my VS2013 as you are using the same with the mentioned changes. I am able to compile and run it successfully. See the attachment.
Just call the function and return it to a variable of the same type.
I am making a little arduino binary calculator.
I have the code run some little math problem: ✓
I convert the answer from decimal to binary: ✓
I loop through the binary answer with a for loop and power on LEDs on a bread board to display the answer: ✗
//First led in pin 2
void setup()
{
Serial.begin(9600);
}
//I have the code run some little math problem:Check
int a=2;
int b=5;
int answer=b-a;
int myNum = answer;
void loop(){
//I convert the answer from decimal to binary:Check
int zeros = 8 - String(myNum,BIN).length();
String myStr;
for (int i=0; i<zeros; i++) {
myStr = myStr + "0";
}
myStr = myStr + String(myNum,BIN);
Serial.println(myStr);
//I loop through the binary answer with a for loop
//and power on LEDs on a bread board to display the answer:Not check
for(int i=2;i<=9;i=i+1){
//This part doesn't work
if(int(myStr[i-2])==1){
digitalWrite(int(i), HIGH);
}else{Serial.println(myStr[i-2]);}
}
while(true){}
}
for some reason it says int(myStr[i-2]) is never equal to 1.
Thanks in advance for the help.
The int() conversion is likely not doing what you think it does. It does not convert the value from a numerical string to a binary value. Instead you probably want to check to see if the values in the string are ascii digits.
if(myStr[i - 2] == '1')
// ^^^ single quotes to specify character value.
{
digitalWrite(int(i), HIGH);
}
else
{
Serial.println(myStr[i - 2]);
}
You should consider that in C a char is nothing more than an alias of an int so casting a char to int is a no-op. So the problem is that you are casting the character '1' or '0' to its int equivalent (its ascii code in fact). You should convert the char to a valid int (by subtracting 48 to a char in the range 48 - 57 you obtain the decimal conversion of the char) or simply checking it against a char value (so myStr[i-2] == '1')
What this code does now: I give int values and it calculates the average between them.
What Ive spent hours on trying to get it do: Ive tried making it so that it would calculate the average between double values. Ive tried everything but it always fails or goes into an infinite loop or will not compile.
Question: So how should I modify my code to make it work with double values/numbers?
#include <stdio.h>
void main()
{
int Tau[10]={0,0,0,0,0,0,0,0,0,0};
int r, i = 0;
int m = 0;
int huku = 0;
do{
printf("Enter numbers: ");
scanf_s("%d", &i);
Tau[m]+=i;
huku++;
}while(i != 0);
r = (Tau[m]/(huku-1));
printf("The average of your numbers is; %d\n", r);
}
You have some issues in your code but basically, integer division will not give you doubles. The result of an integer divided by an integer is another integer, not a double. If you want doubles you need to cast either the numerator or denominator to a double and store the result in a double.
Welcome to Numerical Analysis 1001.
Integer math:
2 / 3 = 0;
4 / 2 = 2;
5 / 2 = 2;
Integers don't do fractions.
I don't see why you need Tau to be a vector in your case. An int would suffice.
huku-1 -> That is wrong. It should be just huku.
You need to cast Tau and huku to double when you divide. It won't hurt to check that huku is != 0 also.
m is useless. Just delete it.
r shouldn't be an int if you wish to store Tau/huku in it.
in printf replace %d with %lf
The simplest changes only involve four lines:
double Tau[10] = {0,0,0,0,0,0,0,0,0,0};
double r, i = 0;
scanf_s("%f", &i);
printf("The average of your numbers is; %f\n", r);
Note that this doesn't address the coding issues; all it does is change the code to read and work with double instead of int.
double r = 0;
int i = 0;
r = ((double)Tau[m]/((double)huku-1));
printf("The average of your numbers is; %f\n", r);
// Question is tagged for C++, but the code is in C.
// I will change your code a bit, because you had quite a few mistakes.
#include <stdio.h>
void main ()
{
int sum = 0; // sum of all numbers you entered, to find average you only need total sum and number of entries
int numOfEntries; // number of entries (numbers taken from input)
int inputNum; // variable where you will write numbers from input one by one
double average; // Not really needed, but it can help to simplify the problem to you.
printf("Enter numbers: ");
do
{
scanf_s("%d", &inputNum);
sum += inputNum;
numOfEntries++;
} while (inputNum != 0); // I understand you read numbers until you read value 0.
// int / int will give you rounded number, not the true average, so we need to convert one of the operands to a real number, in this case double
// double / int or int / double will give you a real number as result, which will have true average value, and that is why I converted sum to a real number
if (numOfEntries != 0)
average = (double)sum / numOfEntries;
else
average = 0;
printf("The average of your numbers is; %f\n", average); // Here I did it again - print double instead of int to get true value.
}
It will be even easier to change this:
....
double sum = 0;
...
average = sum / numOfEntries; // Here sum is already double, not int, so you don't need to change it manually.
...
Now, if you want to make it work for double, the only difference will be:
double sum = 0;
double inputNum;
scanf_s("%lf", &inputNum);
average = sum / numOfEntries;
So, to round up the story - you have variable to input a number from keyboard, a variable which holds sum of all entered numbers so far, a variable which counts how many numbers you entered from keyboard. You input numbers until you enter 0 as value, then the program will exit the loop. Formula for average number is sum of all divided by number of numbers. With integers you have to add conversion to a real number or otherways you won't get accurate result.
I hope I didn't confuse you. :D