How to modify this code to do sequential
program to calculate the wall clock time
(time_t) needed to calculate the dot product
of the complex numbers.
#include "stdafx.h"
#include <stdlib.h>
#include<stdio.h>
typedef struct complex{
double real;
double img;
}complex;
complex add(complex a, complex b);
complex multiply(complex *a, complex *b);
int _tmain(int argc, _TCHAR* argv[])
{
int choice, temp1, temp2;
complex a, b, c;
while (1)
{
printf("Press 1 to add two complex numbers.\n");
printf("Press 2 to multiply two complex numbers.\n");
printf("Press 3 to exit.\n");
printf("Enter your choice\n");
scanf_s("%d", &choice);
if (choice == 3)
exit(0);
if (choice >= 1 && choice <= 2)
{
printf("Enter a and b where a + ib is the first complex number.");
printf("\na = ");
scanf_s("%d", &a.real);
printf("b = ");
scanf_s("%d", &a.img);
printf("Enter c and d where c + id is the second complex number.");
printf("\nc = ");
scanf_s("%d", &b.real);
printf("d = ");
scanf_s("%d", &b.img);
}
if (choice == 1)
{
c.real = a.real + b.real;
c.img = a.img + b.img;
if (c.img >= 0)
printf("Sum of two complex numbers = %d + %di", c.real, c.img);
else
printf("Sum of two complex numbers = %d %di", c.real, c.img);
}
else if (choice == 2)
{
c.real = a.real*b.real - a.img*b.img;
c.img = a.img*b.real + a.real*b.img;
if (c.img >= 0)
printf("Multiplication of two complex numbers = %d + %di", c.real, c.img);
else
printf("Multiplication of two complex numbers = %d %di", c.real, c.img);
}
else
printf("Invalid choice.");
printf("\nPress any key to enter choice again...\n");
}
}
A typical approach is to record time() twice and run the code many times to get a 1st order approximation.
time_t t0,t1;
time(&t0);
int N = 1000000;
for (int i=0; i< N; i++) {
DoCodeUnderTest();
// c.real = a.real + b.real;
// c.img = a.img + b.img;
}
time(&t1);
printf("Time %e\n", (double) (t1-t0) / N);
Suggest using profiling tools for a more accurate answer.
#Jonathan Leffler suggestion to use clock() is also an improvement.
clock_t c1,c12;
c1 = clock();
... // repeat runs of the code
c2 = clock();
printf("Time %e\n", (double) (c1-c0) / CLOCKS_PER_SEC / N);
Given 1) #Jonathan Leffler 2nd suggestion about the legitimacy of repeating since a compiler may out-think the code and 2) cache issues hints that any brute force methods as suggested here are at best illustrative and not definitive time measurements.
Related
I have been trying to program a tool, where I take input from the user if its a circle or square or rectangle and accordingly it will take the measurement inputs and print out the area for the same. But its not working, please help me with what are the problems with my code and how can i get it to work?
#include<stdio.h>
#include<math.h>
float square(float side);
float circle(float rad);
float rect(float a,float b);
int main(){
char lol;
printf("press s for square\n c for circle\n r for rectagle\n");
scanf("%c ", &lol);
if(lol == 's')
{
int t;
printf("enter side measurement");
scanf("%d", &t);
printf("the area is %f", square(t));
}
if(lol == 'c');
{
int r;
printf("enter radius of circle");
scanf("%d", &r);
printf("the area is %f", circle(r));
}
if (lol == 'r')
{
int m,n;
printf("enter 2 sides ");
scanf("%d %d", &m,&n);
printf("the area is %f", rect(m,n));
}
return 0;
}
float square(float side){
return side*side;
}
float circle(float rad){
return 3.14* rad*rad;
}
float rect(float a,float b){
return a*b;
}
Screenshot of execution
You want to remove the trialing ' ' in the first scanf(), and remove the ; after the if statement.
If main() is last you often can get away with not specifying prototypes for small programs like this. Added error checking of scanf(). Prefer if-else-if when the conditions are mutually exclusive, or as here a switch statement so you don't need to repeat the lol == . Prettied up the prompts a bit (colons, newlines), and sorted both the menu and matching implementation. It makes it easier for end-users and easier to navigate for anyone working on the code. math.h defined the constant M_PI if __USE_XOPEN is set. It's better to use a constant than hard-coding the 3.14 value in circle().
#define __USE_XOPEN
#include <math.h>
#include <stdio.h>
float circle(float rad) {
return M_PI * rad * rad;
}
float rect(float a, float b) {
return a * b;
}
float square(float side) {
return side * side;
}
int main(void) {
printf("press:\n"
" c for circle\n"
" r for rectangle\n"
" s for square\n"
);
char lol;
if(scanf("%c", &lol) != 1) {
printf("scanf failed\n");
return 1;
}
switch(lol) {
case 'c': {
printf("enter radius of circle: ");
int r;
if(scanf("%d", &r) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", circle(r));
break;
}
case 'r': {
printf("enter 2 sides: ");
int m, n;
if(scanf("%d %d", &m,&n) != 2) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", rect(m,n));
break;
}
case 's': {
printf("enter side measurement: ");
int t;
if(scanf("%d", &t) != 1) {
printf("scanf failed\n");
return 1;
}
printf("the area is %f\n", square(t));
break;
}
default:
printf("invalid selection %c\n", lol);
}
}
Im writing a code that evolves the computer and I entering numbers and added them together to see who wins.
There are three problems:
Problem 1: When I try to recall the 'main()' function the 'game()' wont appear.
Problem 2: I can't seem to run the code forever until user decides to stop.
Problem 3: The point system isn't accurate enough.
Any help would be grateful.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int human_fingers;
int comp_fingers;
int menu_choice;
int answer;
int count = 1;
int point1 = 0, point2 = 0;
int total;
void intro() {
printf("Welcome to Morra - Odds and Even!\n\n");
printf("The rules of the game are pretty simple\n");
printf("You and the computer will pick a side each round\n");
printf("You must enter a number and the total sum will determine the winner!\n\n");
}
void example() {
printf("You picked even, by default the computer will be odd this round\n");
printf("You entered 3 and the computer entered 5\n");
printf("3 + 5 = 8, so you win because you choose even!\n");
}
void game() {
while(count < 7)
{
count = count + 1;
printf("Enter a number to choose a side:\n");
printf("Even [1] / Odd [2]\n");
scanf("%d", &menu_choice);
while((menu_choice<1) || (menu_choice>2)){
printf("Invalid entry, please Enter 1-2: ");
scanf("%d",&menu_choice);}
if(menu_choice == 1)
{
printf("The computer will be odd this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number....\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 2;
if(total == 0)
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point1++;
}
else
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0 );
printf("Computer: %d\n\n", point2 + 1);
point2++;
}
}
if(menu_choice == 2)
{
printf("The computer will be even this turn\n");
printf("\nPlease enter an number (1-10)\n");
scanf("%d", &human_fingers);
while((human_fingers<1) || (human_fingers>10)){
printf("Invalid entry, please enter 1-10:");
scanf("%d",&human_fingers);}
printf("Computer is choosing a number...\n");
srand(time(NULL));
comp_fingers = rand() % 10 + 1;
printf("You: %d\n", human_fingers);
printf("Computer: %d\n", comp_fingers);
int result;
result = human_fingers + comp_fingers;
printf("Total is %d\n", result);
total = result % 1;
if(total == 0)
{
printf("This turn goes to Computer!\n\n");
printf("You: %d\n", point1 + 0);
printf("Computer: %d\n\n", point2 + 1);
point1++;
}
else
{
printf("This turn goes to You!\n\n");
printf("You: %d\n", point1 + 1);
printf("Computer: %d\n\n", point2 + 0 );
point2++;
}
}
}
if(point1 > point2)
printf("You won, you beat the computer!\n");
else
printf("Unlucky the computer won!\n");
}
void end(){
printf("Game has ended!\n");
}
int main()
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1)
{
main();
}
else {
printf("Thanks for playing MORRA - ODDS AND EVEN.");
}
return 0;
}
Why not:
int main()
{
for(;;) // Infinite loop. -- equivalent of while(1) if you prefer.
{
intro();
printf("Would you like an example to demostrate?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer == 1 )
{ example();
printf("\n\n");
game();
}
else
{ printf("\n\n");
game();
}
end();
printf("Would you like play another game?\n");
printf("Yes [1] / No [2]\n");
scanf("%d", &answer);
if( answer != 1)
{
printf("Thanks for playing MORRA - ODDS AND EVEN.");
break;
//^___ exit the infinite loop.
}
}
return 0;
}
Recalling the main you should definitely not, in almost any case. Just create loops if you want to repeat everything.
I just started programming a couple of days ago. I tried to program something that calculates my CGPA. I haven't completed it yet; for example, I have to improve the menu etc. It works properly for the 1st and 3rd choice. I will do something else for the second choice. The problem is, after calculation, it doesn't print the text "qwerty" on the bottom.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char h[2];
double numGrade;
double credit, percent, overallCredit, sumCredit;
double contribution=0, GPA=0, semGPA=0, CGPA=0;
int courseNum, i, semesters, k, menu;
printf("Input\n\"1\" for computing your CGPA\n\"2\" if you know each semester's GPA\n\"3\" if you know your CGPA\n");
scanf("%d", &menu);
if(menu == 1)
{
printf("Enter the number of semesters you have studied: ");
scanf("%d", &semesters);
for(k=1; k<=semesters; k++)
{
printf("Enter the number of courses you took in semester %d: ", k);
scanf("%d", &courseNum);
overallCredit = 0;
sumCredit = 0;
for(i=1; i<=courseNum; i++)
{
printf("Enter the credit of the course %d: ", i);
scanf("%lf", &credit);
overallCredit += credit;
printf("Enter your letter grade: ");
scanf("%s", h);
if(strcmp(h, "AA") == 0)
{
numGrade = 4.0;
}else if(strcmp(h, "BA") == 0)
{
numGrade = 3.5;
}else if(strcmp(h, "BB") == 0)
{
numGrade = 3.0;
}else if(strcmp(h, "CB") == 0)
{
numGrade = 2.5;
}else if(strcmp(h, "CC") == 0)
{
numGrade = 2.0;
}else if(strcmp(h, "DC") == 0)
{
numGrade = 1.5;
}else if(strcmp(h, "DD") == 0)
{
numGrade = 1.0;
}else if(strcmp(h, "FD") == 0)
{
numGrade = 0.5;
}else if(strcmp(h, "DD") == 0)
{
numGrade = 0.0;
}else
{
printf("Invalid Grade\n");
}
percent = numGrade/4.0;
contribution = percent*credit;
sumCredit += contribution;
}GPA = (sumCredit/overallCredit)*4.0;
printf("Your GPA for semester %d is: %f\n", k, GPA);
semGPA += GPA;
}CGPA = semGPA/semesters;
printf("CGPA is: %.2f", CGPA+0.005);
}else
{
printf("Enter your CGPA: ");
scanf("%lf", &CGPA);
printf("Your CGPA is: %.2f", CGPA+0.005);
}
printf("qwerty"); //This does not print.
return 0;
}
The problem here is that you're running into undefined behaviour! (This means anything can happen - code will work, sometimes, not work, sometimes, and maybe even wipe your hard disk, sometimes.)
This happens because you are trying to read too many characters into your h variable: you have declared it: char h[2], which can hold only one letter plus the terminating nul. But you try to read two letters into it. Declare it a bit longer: char h[3] and your code should work. But it's maybe better to be safer, and declare it longer, say char h[20];, in case the user types too much data in; alternatively, specify in the input format a maximum string length: scanf("%2s", h);, which will truncate (ignore) any letters after the second.
In your code, the scanf operation writes beyond the memory allocated to h and, thus, maybe changes other 'control' variables in the compiled code.
EDIT: PS, it may not actually be the scanf call that triggers the undefined behaviour! It could be the subsequent strcmp call - the h argument to this will not have a nul terminator and the function will then overflow the string buffer, looking for a zero.
I am using Microsoft Visual Stusio 2013 Community Edition Update 4 to write a program in the C programming language (not C++). Whenever I try to build and run my program, partway through execution it tells me "Unhandled exception at 0x52873FD4 (msvcr120d.dll) in program.exe: 0xC0000005: Access violation writing location 0x00C40000." When I copy and paste the contents of the .c file into another IDE (code blocks) it compiles and runs without a problem. (Although I do have to change all the scanf_s statements in the code to scanf)
The source code from within the .c file of my program
#include <math.h>
#include <stdio.h>
#include <string.h>
#define PI 3.14159265358979323846;
double add();
double cos_d_r();
double div();
double mult();
void list();
int main()
{
//Declaration of variables
char oper[20];
double ans;
int loop = NULL;
//While loop allows for multiple executions without restarting program
while (!loop)
{
printf("\n\nEnter a mathematical operation.\n\nFor a list of options, enter 'list'\n\n");
scanf_s(" %s", oper);
//If statement to determine which operation to do
//Addition
if (strcmp(oper, "add") == 0 || strcmp(oper, "addition") == 0 || oper[0] == '+')
{
ans = add();
printf("The sum is %.2f\n", ans);
}
//Cosine
else if (strcmp(oper, "cos") == 0 || strcmp(oper, "cosine") == 0)
{
ans = cos_d_r();
printf("The cosine of the angle is %lf\n", ans);
}
//Division
else if (strcmp(oper, "divide") == 0 || strcmp(oper, "division") == 0 || oper[0] == '/')
{
ans = div();
printf("The quotient is %.2f\n", ans);
}
//List of possible operations
else if (strcmp(oper, "list") == 0)
{
list();
}
//Multiplication
else if (strcmp(oper, "multiply") == 0 || strcmp(oper, "multiplication" == 0) || oper[0] == '*')
{
ans = mult();
printf("The product is %.2f", ans);
}
}
return 0;
}
//Declaration of functions
//Addition
double add()
{
double ans;
double num_1;
double num_2;
puts("Enter the first number");
scanf_s(" %lf", &num_1);
puts("Enter the second number");
scanf_s(" %lf", &num_2);
ans = num_1 + num_2;
return ans;
}
//Cosine
/*Uses cos() function from math.h
this function adds option for degrees or radians*/
double cos_d_r()
{
char deg_rad;
double angle;
double ans;
int loop = NULL;
while (!loop)
{
puts("Degrees or radians? Enter 'd' or 'r'");
scanf_s(" %c", °_rad);
//Degrees
if (deg_rad == 'd')
{
puts("Enter an angle in degrees");
scanf_s(" %lf", &angle);
angle = angle / 180 * PI;
ans = cos(angle);
loop = 1;
return ans;
}
//Radians
else if (deg_rad == 'r')
{
puts("Enter an angle in radians");
scanf_s(" %lf", &angle);
ans = cos(angle);
loop = 1;
return ans;
}
//Else statement repeats loop if user enters text other than 'd' or 'r'
else
{
puts("ERROR. Enter either 'd' or 'r'");
}
}
}
//Division
double div()
{
double ans;
double num_1;
double num_2;
puts("Enter the dividend");
scanf_s(" %lf", &num_1);
puts("Enter the divisor");
scanf_s(" %lf", &num_2);
ans = num_1 / num_2;
return ans;
}
//Multiplication
double mult()
{
double ans;
double num_1;
double num_2;
puts("Enter the first number");
scanf_s(" %lf", &num_1);
puts("Enter the second number");
scanf_s(" %lf", &num_2);
ans = num_1 * num_2;
return ans;
}
//List of possible operations
void list()
{
printf("The possible operations are:\n\n");
printf("Operation\tDescription\tCommand");
printf("Addition\tAdds two numbers together\tAdd, Addition, +\n");
printf("Cosine\tFinds the cosine of the angle entered\tCos, Cosine");
printf("Division\tDivides the first number by the second\tDivide, Division, /");
printf("Multiplication\tMultiplies the two numbers\tMultiply, Multiplication, *");
}
You should read description of functions you use first! Take a look at scanf_s function description at MSDN. You programm crashes at first call of this function
scanf_s(" %s", oper);
The correct way to use it:
scanf_s("%s", oper, _countof(oper)); // or sizeof(oper), but only with char array
Also you should correct other calls of scanf_s in your code. (Or disable errors for scanf call with #define _CRT_SECURE_NO_WARNINGS before #include <stdio.h>)
I need to write a simple program in C that makes simple calculations of: +,-,*,/
Now, I am using Visual Studio Express 2013, and here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf_s("%c", &o);
printf("Enter first operand\n");
scanf_s("%f", &a);
printf("Enter second operand\n");
scanf_s("%f", &b);
if (o == '+'){
sum = a + b;
printf("The result is", &sum);
}
if (o == '-'){
sum = a - b;
printf("The result is", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is", sum);
}
else printf("Error");
}
getchar();
}
My output: Enter operator
+
Enter first operand
3.5
Enter second operand
5.4
And after I type the second number- the program exits, and nothing!
There are no compilation errors, and I have no idea what to do. Can someone help, please?
You're not using printf correctly. This is what you're using.
printf("The result is", &sum);
You're not specifying the type of output in the format string, and you're passing the address of the variable you want to print, not the value.
You should use:
printf("The result is %lf\n", sum);
%lf is specifying that you want to print a double, \n adds a newline, and you pass the value of the variable sum, not it's address.
Also, you should change if (b == !0){ to if (b != 0){. If you leave what you put, it's the equivalent to if (b == 1){, which probably isn't what you want.
EDIT Here is the code, with my modifications, which gives correct results. I'll indicate which lines I changed
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
/* I had to use scanf, since I'm not using MS/Visual Studio, but GCC */
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%lf", &a); /* changed %f to %lf */
printf("Enter second operand\n");
scanf("%lf", &b); /* changed %f to %lf */
/* I prefer to use if ... else if ..., this is personal preference */
if (o == '+'){
sum = a + b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '-'){
sum = a - b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '*'){
sum = a*b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '/'){
if (b != 0){
sum = a / b;
printf("The result is %lf\n", sum); /* Changed, see original post */
}
else printf("Error");
}
getchar();
return 0;
}
You are using %f format to read doubles. You should use %lf:
scanf_s("%lf", &a);
The print methods actually don't print the result (format is incomplete). And, instead of the value, you are passing variable's address. It should be:
printf("The result is %e", sum);
You should also change if (b == !0) to if (b != 0)
Now it's working fine I made some changes to it
the problem was with ur "scanf_s" and "%f" go throw with it
#include<stdio.h>
#include<stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%d", &a);
printf("Enter second operand\n");
scanf("%d", &b);
if (o == '+'){
sum = a + b;
printf(" The result is %d", sum);
}
if (o == '-'){
sum = a - b;
printf("The result is %d", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is %d", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is %d", sum);
}
else printf("Error");
}
getchar();
}