Math functions in C
I am using Code::blocks to compile my first multiple source file, learned from "C Programming in easy steps" by Mike McGrath. Unfortunately my math functions seem to be having issues. Here's the header that contains the functions:
/* this header file contains utility functions */
int square(int x); /* function prototypes */
int multiply(int x, int y);
int square(int x)
{
return (x*x);
}
int multiply(int x, int y)
{
return (x*y);
}
The only function having the problem is "square()". It reads the input of "2" as "2293356" and outputs the square as "553755367"... What the heck?!?
Here's the menu.c file... There's menu.c, ops.c, calc.c, and utils.h. Abaov is the .h. MENU.c include
void menu();
void menu()
{
int num;
printf("\n\tEnter the number of an operation:\n");
printf("\t1. Square a number\n");
printf("\t2. Multiply two numbers\n");
printf("\t3. Exit\n");
scanf("%d", &num);
switch(num)
{
case 1 : getnum(); break;
case 2 : getnums(); break;
case 3 : return;
}
}
Here's ops.c...
#include <stdio.h>
#include "utils.h"
void getnum();
void getnums();
void getnum()
{
int num;
printf("Enter an integer to be squared: ");
scanf("%d", &num);
printf("%d squared is %d\n, num, square(num)");
menu();
}
void getnums()
{
int num1, num2;
printf("Enter two numbers to be multiplied, ");
printf("seperated by a space: ");
scanf("%d", &num1);
scanf("%d", &num2);
printf("%dx%d = %d\n", num1, num2, multiply(num1, num2));
menu()开发者_JAVA技巧;
}
This is the last part of the program, calc.c,
#include <stdio.h>
int main()
{
menu();
printf("end\n");
return 0;
}
The square of 2293356 doesn't fit into int
and therefore overflows which leads to undefined behavior! As to why it reads 2 as 2293356 cannot be answered without more code.
Update: And here's your real error:
printf("%d squared is %d\n, num, square(num)");
should be
printf("%d squared is %d\n", num, square(num));
:)
精彩评论