[英]How do you use a function twice for two different equations?
無論如何,這還是編碼的新問題:
編寫一個使用函數將兩個數字相乘並返回結果的程序。 在您的程序中,使用函數將值3和4相乘,然后再次使用函數將值num1和num2相乘,其中用戶輸入了num1和num2。 將結果打印到屏幕上。
不太確定如何將相同的函數用於2種不同的計算。 我還能做其他的事...
int multiply (int a, int b)
{
int result;
a = 3;
b = 4;
result = a * b;
return result;
}
int main (void) {
int n1,n2,three,four, sum, result;
result = multiply(three,four);
printf("result is = %d \n \n", result);
printf("Please enter 2 int values: \n \n");
scanf("%d %d", &n1, &n2);
sum = multiply(three,four);
three = n1;
four = n2;
printf("sum is = %d", sum);
system("pause>nul");
return 0;
}
我認為:
int multiply (int a, int b)
{
return a * b;
}
您的代碼具有相同的結果,因為您將值分配給了函數中的變量。
要將相同的功能用於2個不同的操作。 打電話兩次。 第二次使用從用戶那里收到的值。 第一次函數將使用內置參數。
靜態int s
會記住您調用了函數。
#include <stdlib.h>
#include <stdio.h>
int multiply (int a, int b)
{
static int s = 0;
if(s==0)
{
a = 3;
b = 4;
s++;
return a*b;
}
else
{
return ( a * b);
}
}
int main (void) {
int n1,n2,three=3,four=4, sum, result;
result = multiply(three,four);
printf("result is = %d \n", result);
printf("Please enter 2 int values:\n");
scanf("%d %d", &n1, &n2);
sum = multiply(n1,n2);
printf("result is = %d\n", sum);
return 0;
}
輸出:
result is = 12
Please enter 2 int values:
4 4
result is = 16
您的功能所需要做的就是將兩個值相乘:
int multiply (int a, int b)
{
return a * b;
}
使用此函數進行兩種不同計算的方式是傳遞不同的參數。
首先,您可以使用它乘以3乘以4:
result = multiply(3, 4);
然后使用它將用戶輸入的兩個數字相乘:
printf("Please enter 2 int values: \n \n");
scanf("%d %d", &n1, &n2);
result = multiply(n1 ,n2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.