
C语言零基础入门习题(八)四则运算
前言
C语言是大多数小白走上程序员道路的第一步,在了解基础语法后,你就可以来尝试解决以下的题目。放心,本系列的文章都对新手非常友好。
Tips:题目是英文的,但我相信你肯定能看懂
一、四则运算 题目(Math tutor) Write a program that displays a menu as shown in the sample run. You can enter 1, 2, 3, or 4 for choosing an addition, subtraction, multiplication, or division test. After a test is finished, the menu is redisplayed. You may choose another test or enter 5 to exit the system. Each test generates two random single-digit numbers to form a question for addition, subtraction, multiplication, or division. For a subtraction such as number1 – number2, number1 is greater than or equal to number2. For a division question such as number1 / number2, number2 is not zero.
<Output>
Main menu
1: Addition
2: Subtraction
3: Multiplication
4: Division
5: Exit
Enter a choice: 1<enter icon>
What is 1 + 7? 8<enter icon>
Correct
Main menu
1: Addition
2: Subtraction
3: Multiplication
4: Division
5: Exit
Enter a choice: 1<enter icon>
What is 4 + 0? 5<enter icon>
Your answer is wrong. The correct answer is 4
Main menu
1: Addition
2: Subtraction
3: Multiplication
4: Division
5: Exit
Enter a choice: 4<enter icon>
What is 4 / 5? 1<enter icon>
Your answer is wrong. The correct answer is 0
Main menu
1: Addition
2: Subtraction
3: Multiplication
4: Division
5: Exit
Enter a choice:
<End Output>
二、代码示例 #include <stdio.h> #include <stdlib.h> #include <time.h> int ranNum (void); void printIn (int); int main() { int a,n1,n2,c; while(a!=5) { n1=ranNum (); n2=ranNum (); printf("Main menu\\n1: Addition\\n2: Subtraction\\n3: Multiplication\\n4: Division\\n5: Exit\\nEnter a choice: "); scanf("%d",&a); if (a==1) { printf("What is %d + %d?",n1,n2); c=n1+n2; printIn (c); } if (a==2) { printf("What is %d - %d?",n1,n2); while (n1<n2) { n1=ranNum (); } c=n1-n2; printIn(c); } if (a==3) { printf("What is %d * %d?",n1,n2); c=n1*n2; printIn(c); } if (a==4) { printf("What is %d / %d?",n1,n2); while (n2==0) { n2=ranNum (); } c=n1/n2; printIn(c); } } return 0; } int ranNum () { int n; srand (time(NULL)+rand()); n=rand()%10; return (n); } void printIn(int c) { int b; scanf("%d",&b); if (b==c) printf("Correct\\n\\n"); else printf("Your answer is wrong. The correct answer is %d\\n\\n",c); }总结
以上就是本文全部内容,你学会了吗?