So the program is supposed to calculate the temperature from an initial temp given by the user which is then changed based on wind, humidity, and condition. first get a starting temperature from the user, then display a menu of choices that consist of entering wind speed, entering humidity, entering the condition, displaying the current temperature, displaying the last 1000 temperatures after the initial temp has been modified and displaying the sum of all temperatures.
I have done most of it but I'm having problems with how to store and display the last 1000 temperatures. I'm supposed to use an array in this program but I'm not sure how to use it to get what I need. Help, please.
#define _CRT_SECURE_NO_WARNINGS
#define CLS system("cls")
#define PAUSE system("pause")
#include <stdio.h>
#include <stdlib.h>
// PROTOTYPING FUNCTIONS
void askTemp();
float convertC(float f);
void displayMenu();
char getChoice();
char getCondChoice();
float getHumid();
float getTemp();
float getWind();
main() {
// INITIALIZE VARIABLES
float temp;
float wind = 5;
float humid = 20;
int trump = 0;
char choice = 'A';
int num;
char cond = 'S';
char condChoice;
float celsius;
int i = 0;
int j = 0;
int k = 0;
float temp2 = 0;
float wind2 = 0;
float humid2 = 0;
int x = 0;
askTemp();
temp = getTemp();
do{
displayMenu();
choice = getChoice();
switch (choice){
case 'W': // Get Wind
wind = getWind();
break;
case 'H': // Get the humidity
humid = getHumid();
break;
case 'C': // Enter subswitch statement to get condition
condChoice = getCondChoice();
switch (condChoice){ // gets condition
case 'S':
cond = 'S';
break;
case 'C':
cond = 'C';
break;
case 'R':
cond = 'R';
break;
}// END SWITCH
case 'T': // display current temperature
if (temp != temp2 || wind != wind2 || humid != humid2){ // apply degree changes based on humid, wind, and cond
if (wind > 100)
temp = temp - (temp * .03);
if (wind < 10)
temp = temp + (temp * .025);
if (humid > 75)
temp = temp + (temp * .058933);
if (humid < 20)
temp = temp - (temp * .0162);
if (cond == 'S' && wind > 30)
temp = temp + (temp * .01);
if (cond == 'S' && wind == 0)
temp = temp + (temp * .005);
if (cond == 'R')
temp = temp - (temp * .02);
if (cond == 'C' && humid > 75)
temp = temp + (temp * .01);
if (cond == 'C' && humid < 75)
temp = temp + (temp * .005);
if (wind > 30 && humid > 75 && cond == 'S')
temp = temp;
wind2 = wind; // assigned variables so program does not apply condition changes multiple times for same temp
humid2 = humid;
temp2 = temp;
}// END IF
celsius = convertC(temp2);
printf("The Current temperature is %.1ff/%.1fc degrees Celsius\n", temp2, celsius);
PAUSE;
break;
case 'P': // Display previous 1000 temperatures
break;
case 'A': // Display average of all temps entered
break;
}// END SWITCH
} while (choice != 'Q');
} // END MAIN
void askTemp(){
printf("What is the current temperature: \n");
return;
}// end askTemp
void displayMenu(){
CLS;
printf("W. Enter Wind Speed\n");
printf("H. Enter Humidity\n");
printf("C. conditions\n");
printf("T. Current Temperature\n");
printf("P. Previous Temps\n");
printf("A. Average Temperature\n");
printf("Q. Quit\n");
return;
} // end currentTemp
char getChoice(){
char result;
scanf("%c", &result);
result = toupper(result);
return result;
}// end getChoice
char getCond(){
char result;
}// end getCond
char getCondChoice(){
char result;
printf("S for sunny, C for cloudy, R for rainy\n");
scanf(" %c", &result);
result = toupper(result);
do{
if (result != 'S' && result != 'C' && result != 'R'){
printf("Invalid input try again\n");
scanf(" %c", &result);
result = toupper(result);
}
} while (result != 'S' && result != 'C' && result != 'R');
return result;
}// end getCond
float getHumid(){
float result;
scanf("%f", &result);
return result;
}// end getHumid
float getTemp(){
float result;
scanf("%f", &result);
do{
if (result < -50 || result > 150){
printf("Invalid temperature try again\n");
scanf("%f", &result);
}
} while (result < -50 || result > 150);
return result;
}// end getTemp
float getWind(){
float result;
scanf("%f", &result);
return result;
}// end getWind
float convertC(float f){
float t;
t = (f - 32) / 1.8;
return(t);
}// end convert
You declare an array of 1000 float like this:
float saved_temperatures[1000];
You store a value in it by indexing into the array, and using it like a variable.
saved_temperatures[i] = temp;
++i;
i is an indexing variable, and you should make sure it starts at zero and is always less than 1000. The valid index range for saved_temperatures is 0..999.
for (int i = 0; i < 1000; ++i) {
printf("index %d temperature %f\n", i, saved_temperatures[i]);
}
Related
I have a coding assignment for my CIS class. The assignment is to write a program the will create an array of structures that will hold information on at max 10 dogs. At the end of the program, you are supposed to sort the array of dogs by either name or size. But I am unable to code the sorting of the array of dog. I was wondering how to sort the array of dogs for later use in the main function.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Dog{
char name[20];
int weight;
int age;
int ageDogYears;
char size[7];
};
typedef struct Dog DG;
void calc(DG[], int);
void sort(DG[], int);
void display();
int main(){
DG dArray[10];
int x = 0;
char str[80], *i;
FILE *inFile;
inFile = fopen("dogfile.txt", "r");
if (inFile == NULL){
printf("Error opening file");
exit(1);
}
while(fgets(str, 80,inFile) != NULL){
i = strtok(str, ", ");
strcpy(dArray[x].name, i);
puts(dArray[x].name);
i = strtok(NULL, ", ");
dArray[x].weight = atoi(i);
printf("%d\n", dArray[x].weight);
i = strtok(NULL, ", ");
dArray[x].age = atoi(i);
printf("%d\n", dArray[x].age);
x++;
}
calc(dArray, x);
sort(dArray, x);
return 0;
}
void calc(DG dog[], int numDogs){
int y, i, total;
for(i = 0; i < numDogs; ++i){
if(dog[i].weight <= 20){
//sets the dog size to small
strcpy(dog[i].size, "Small");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 15;
else if(y == 1)
total += 8;
else if(y == 2)
total += 5;
else
total += 4;
}
}
else if(dog[i].weight <= 50){
//sets the dog size to medium
strcpy(dog[i].size, "Medium");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 14;
else if(y == 1)
total += 9;
else if(y == 2)
total += 7;
else
total += 5;
}
}
else{
//sets the dog size to Large
strcpy(dog[i].size, "Large");
for(y = 0; y < dog[i].age; ++y){
if(y == 0)
total += 12;
else if(y == 1)
total += 9;
else if(y == 2)
total += 8;
else
total += 7;
}
}
dog[i].ageDogYears = total;
total = 0;
}
}
void sort(DG dog[], int numDogs){
int sortType, i, y, temp;
printf("\n wlould you like to sort by name(N) or size(S): ");
scanf("%c", &sortType);
switch(sortType){
case 'N': case 'n':
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs); ++y){
if(dog[y].weight > dog[y+1].weight){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
break;
default:
if((sortType != 's') && (sortType != 'S'))
printf("\n invalid input! Setting sort type to size.");
//sorting of dog names
}
}
Sample Input
Fluffy,23,6
Fido,65,7
Pepper,44,5
Bowser,75,10
Victor,10,2
Sassy,51,1
Any help would be much appretated! Thanks.
In my opinion, your error resides (despite of other comments I'll do below) in specifying %c as format descriptor to pass a pointer to int to match. You have to pass a pointer to char to make scanf(3) to select the proper place to put the character into. You probably are not getting the right character or no character at all (this leads to Undefined Behaviour in your program)
Some other problems are that you are using the weight field of the structure when requested to sort by name (on n input char) and other errors like this. This includes that you use y < (numDogs) in the inner loop limit condition (it must be y < (numDogs - 1), or you'll compare the y-esim with the y+1-esim element (out of array bounds)
Also, as you are using the same algorithm for both sorting options, I should include the switch statement inside the inner loop (where you do the comparison) as doing otherwise will force you to copy the same sorting code twice (for the overall sorting algorithm), as in:
for(i = 0; i < numDogs; ++i){
for(y = 0; y < (numDogs - 1); ++y){
int sortResultGreater;
switch (sortType) {
case 'n': case 'N':
sortResultGreater = strcmp(dog[y].name, dog[y+1].name) > 0;
break;
default: { /* this should be done as soon as you know the sorting type, not here inside the loop, of course */
static int not_already_printed = 1;
if (not_already_printed) {
printf("Error, sortType must be [nNsS], defaulting to n\n");
not_already_printed = 0; /* so we don't get here again */
}
} /* scope of not_already_printed finishes here */
/* no break used here to fallback to the next case */
case 's': case 'S':
sortResultGreater = dog[y].weight > dog[y+1].weight;
break;
} /* switch */
if(sortResultGreater){
temp = dog[y];
dog[y] = dog[y + 1];
dog[y + 1] = temp;
}
}
}
I am trying to write code that says if there is command line input then do something if not do something else.
int main(int argc, char *argv[])
{
int lowerBound, upperBound, i, count = 0;
float val;
char c;
if(argc = 2)
{
lowerBound = argv[1];
printf("Lower bound = %d", lowerBound);
item * curr, * head;
head = NULL;
do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));
if(val >= lowerBound)
{
curr->num = val;
curr->next = head;
head = curr;
count++;
}
getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );
curr = head;
float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
else if(argc = 3)
{
lowerBound = argv[1];
upperBound = argv[2];
printf("Lower bound = %d", lowerBound);
printf("Upper bound = %d", upperBound);
item * curr, * head;
head = NULL;
do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));
if(val >= lowerBound && val <= upperBound)
{
curr->num = val;
curr->next = head;
head = curr;
count++;
}
getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );
curr = head;
float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
else if(argc = 1 or argc = 0 or argc = NULL)
{
item * curr, * head;
head = NULL;
do
{
printf("Enter a number: ");
scanf("%f", &val);
curr = (item *)malloc(sizeof(item));
curr->num = val;
curr->next = head;
head = curr;
count++;
getchar();
printf("Want to enter another number (y/n): ");
scanf("%c", &c);
} while( c != 'n' && c != 'N' );
curr = head;
float largest = findLargest(curr);
float lowest = findSmallest(curr);
float mean = findMean(curr, count);
int ValuesAboveMean = valuesAboveMean(curr, mean);
int ValuesBelowOrAtMean = valuesBelowOrAtMean(curr, mean);
float median = findMedian(curr, count);
show(count, lowest, largest, mean, median, ValuesAboveMean, ValuesBelowOrAtMean);
}
For some reason or another currently, it ignores what is in the if statements and runs whatever is in the if. For instance, even if I have no command line arguments, it still wants to run the first if where arg = 2.
What am I doing wrong and how can I fix it?
You need to make that if(argc == 2)
(instead of if(argc = 2), which assigns 2 to argc and will always be true). I never liked the way C defined = versus == . Some compilers will produce a warning for this.
I'm learning starting to learn C, so I tried to make a simple program with what I know. The program SHOULD ask for a letter, ask if you want the position of a letter in the alphabet(if so it displays "x is the y letter in the alphabet" with the suffix) and then it asks if you want the letter in binary and puts it in binary. But for some reason it doesn't work. I tried "manual debugging"(using puts() to see what doesn't work) and the class "getNumber" works but the value changes when it goes to the main class.
a returns "2686719" instead of "a is the 1st letter in the alphabet" and b returns "2b is the 2z\<<y in the alphabet".
This is the code, what did I do wrong?
#include <stdio.h>
#include <stdlib.h>
//011
int main(){
int x = 2;
char letter;
puts("Write a letter");
char temp2;
scanf("%c", &temp2);
int number;
letter = temp2;
puts("get alphabet position? y/n ");
char temp[2];
scanf("%s", temp);
char answer = temp[0];
int tempNumber2 = getNumber(letter);
if(answer == 'y'){
char suffix[3];
int number = tempNumber2;
printf("%d", number);
if (number == 1){
x = 1;
suffix[0] = "s";
suffix[1] = "t";
}else if (number < 27){
suffix[0] = "t";
suffix[1] = "h";
x = 1;
}
if (x == 1){
printf("%c is the %d", letter, number);
printf("%s in the alphabet\n", suffix);
}}else if (answer == 'n'){
x = 1;
}else if (answer != 'y' && answer != 'n'){
puts("ERROR, invalid letter");
x = 3;
};
if(x != 3){
puts("Convert to binary?");
}
return 0;
}
int getNumber(letter){
char tempLetter = letter;
int tempNumber = -1;
char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
int i = 0;
while(i < 27){
i++;
if(tempLetter == alphabet[i]){
tempNumber = i;
tempNumber++;
printf("%d \n", tempNumber);
return tempNumber;
}
};
}
By the way, I haven't gotten to the binary part hence why it's empty.
As everyone stated in the comments your problem is that suffix's last char is not set to '\0'.
Moreover, you could getNumber in a much simpler way:
int getNumber(char letter) {
return (int)(letter - 'a') + 1;
}
Btw, you can make your code look a little better (didn't change it too much):
int main() {
char letter;
char answer;
puts("Write a letter");
scanf("%c", &letter);
getchar(); // read \n
puts("get alphabet position? y/n ");
scanf("%c", &answer);
getchar(); // read \n
if (answer == 'n') {
return 0;
}
if (answer != 'y') {
puts("ERROR, invalid letter");
return 1;
}
int number = getNumber(letter);
char suffix[3];
suffix[2] = 0;
if (number == 1) {
suffix[0] = 's';
suffix[1] = 't';
} else if (number == 2) {
suffix[0] = 'n';
suffix[1] = 'd';
} else if (number == 3) {
suffix[0] = 'r';
suffix[1] = 'd';
} else {
suffix[0] = 't';
suffix[1] = 'h';
}
printf("%c is the %d%s letter in the alphabet\n", letter, number, suffix);
puts("Convert to binary?");
return 0;
}
When the function recordWeight() is executed and i enter the weight via scanf it works but then at the end it says "invalid input" which is a printf from the function getChoice used in the switch Choice, this "invalid input" message is ment to only appear when you choose the wrong option for the switch.
it isnt supposed to affect the functions in the switch.
and i think it may be preventing values from appearing in the displayHistory() function...
I would really appreciate any help!
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#define pause system("pause")
#define cls system("cls")
#define SIZE 50
#define flush fflush(stdin)
char getChoice();
void displayMenu();
void recordWeight(float a[], int *c);
void displayAverage(float a[], int c);
void highLow(float a[], int c);
void displayHistory(float a[], int c);
main(){
int counter = 0;
float weight[SIZE]={0.0};
char choice;
do {
choice = getChoice();
switch(choice){
case 'A':
recordWeight(weight,&counter);
break;
case 'B':
displayAverage(weight,counter);
break;
case 'C':
highLow(weight, counter);
break;
case 'D':
displayHistory(weight, counter);
break;
}//end switch
}while (choice != 'E' );
}//end main
char getChoice(){
char result = 0;
do{
displayMenu();
scanf_s("%c", &result);
flush;
if(result != 'A' && result != 'B' && result != 'C' && result != 'D' && result != 'E'){
printf("Invalid Selection\n");
pause;}
} while(result != 'A' && result != 'B' && result != 'C' && result != 'D' && result != 'E');
return result;
}//end getChoice
void displayMenu(){
cls;
printf("Main Menu\n");
printf("A) Record Weight\n");
printf("B)Display Average Weight\n");
printf("C)Display Highest and Lowest Weight\n");
printf("D)History of recorded Weight\n");
printf("E)QUIT!!!!\n\n");
printf("Please Enter your selection: \n");
return;
}//end displayMenu
void recordWeight(float *a,int *c){
printf("please enter a your weight..\n");
scanf("%f", &a[*c]);
*c = *c + 1;
if(c > 0){
if(a[*c]>a[*c-1])
printf("Good, You gained weight!\n");
else if(a[*c] < a[*c-1])
printf("Ew You lost weight!\n");
else
printf("Your still the same weight as before...gain some weight!\n");
pause;
}
}//end recordWeight
void displayAverage(float a[], int c){
float average, total = 0.0;
int i;
if(c> 0){
for(i=0; i < c; i++)
total = total + a[i];
average = total/ c;
printf("\nYour Average weight is %.2f\n",average);
pause;}
else
printf("You must enter atleast one weight in order to use this function.");
pause;
}
void highLow(float a[],int c){
if(c > 0){
float high= a[0], low= a[0];
int i;
for(i=0; i < c; i++){
if(a[i]> high)
high= a[i];
if(a[i]<low)
low = a[i];
}
printf("The thinest you have been is %i pounds\n", low);
printf("The Fattest you have been is %i pounds\n", high);
pause;}
else
printf("You must enter atleast one weight in order to use this function.\n");
pause;
}//end highLow
void displayHistory(float a[],int c){
int i;
if(c > 0){
for(i=0;i < SIZE; i++)
printf(" %i. You were %i pounds\n",i+1,a[i]);
}
else
printf("You must enter atleast one weight in order to use this function.\n");
pause;
}//end displayHistory
Your problem is that the input for the weight leaves the newline in the input buffer. Your "%c" format therefore gets the newline, which is not A or B or C or D or E and triggers the warning.
Your simplest fix is to use the format " %c" with a blank before the %c; this will skip whitespace, including newlines, before reading a non-blank character.
I'm writing a simple calculation program and I can't get any valid output. All I'm getting is an upside down question mark. Also, I have a prompt at the end of the program to ask the user if they would like to enter in another calculation. However, when I enter a calculation the prompt comes up twice in the console. Does anyone know why these things are happening? Lastly, I can only use getchar and putchar to handle the input and output. Thanks in advance for the help.
int addFunction( int, int);
int subtractFunction(int, int);
int multiplyFunction(int, int);
int modulusFunction(int, int);
float divideFunction(float, float);
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, result = 0;
char continuePrompt, iochar = 0, operator = 0;
do {
iochar = getchar();
getchar();
if ((iochar >= 0) && (iochar <= 20000)) {
num1 = iochar;
}
if ((iochar == '+') || (iochar == '-') || (iochar == '*') || (iochar == '/') || (iochar == '%')) {
operator = iochar;
}
if ((num1 >= 0) || ((iochar >= 0) && (iochar <= 20000))){
num2 = iochar;
}
switch (operator) {
case '+':
iochar = addFunction(num1, num2);
break;
case '-':
iochar = subtractFunction(num1, num2);
break;
case '*':
iochar = multiplyFunction(num1, num2);
break;
case '%':
iochar = modulusFunction(num1, num2);
break;
case '/':
iochar = divideFunction(num1, num2);
break;
}
putchar(iochar);
printf("Would you like to make another calulation? (y or n)");
scanf("%c", &continuePrompt);
} while (continuePrompt != 'n');
return 0;
}
int addFunction(int x, int y){
return x + y;
}
int subtractFunction(int x, int y){
return x - y;
}
int multiplyFunction(int x, int y){
return x * y;
}
int modulusFunction(int x, int y){
return x % y;
}
float divideFunction(float x, float y){
return x / y;
}
The function getchar and gets a character from the console and putchar puts a character to the console. The are not general input/output functions. Your code reads like you expect getchar to read in decimal representations of integers and putchar to print decimal representation of integers, but they don't work that way. Since you can only use getchar and putchar, you are going to have to write your own input/output methods with them to parse your inputs and display them correctly. So, first, figure out how to parse and output integers. Then use those methods where you're expecting to read or write integers (and floats if you have to display the estimated values for division). It may help to have a helper method that actually grabs the "current" numerical string from wherever you are in the expression.
Some basics...
A character value '0' does not equal the integer value 0 on in ascii it has the integer value 48. If you're only having each number be 1 digit, it would be something like:
char c = getchar();
// Assuming the user only will input a number...
int number = c - '0';
For reading in an integer with just getchar() I would do something like:
#include <stdio.h>
#include <math.h> // for pow
int getint()
{
char c;
char buffer[255]; // way larger than an integer will ever be I think...
int numlen = 0;
int number = 0;
int x;
int multfornegative = 1;
while ((c = getchar()) != '\n') {
buffer[numlen++] = c;
}
for (x = numlen - 1; x >= 0; x--) {
c = buffer[(numlen - 1) - x];
if (c == '-') {
multfornegative *= -1;
} else {
number += (c - '0') * (int)pow(10, x);
}
}
return number * multfornegative;
}
for output you would do something like...
void putint(int number)
{
char digit;
int x;
int start;
if (number < 0) {
putchar('-');
number *= -1;
}
start = log(number) / log(10);
for (x = start; x >= 0; x--) {
digit = ((number / (int)pow(10, x)) % 10) + '0';
putchar(digit);
}
}
Also, try to break apart your input, the way you have it in the loop ends up confusing which is messing up your logic.
int num1;
char op;
int num2;
int ans;
do {
num1 = getint();
op = getchar(); getchar();
num2 = getint();
switch(op) {
case '+': ans = num1 + num2; break;
case '-': ans = num1 - num2; break;
// And so on...
}
putint(ans);
while (1);
The C Programming Language is an amazing book to read for learning C, written by the inventors of C themselves.