我必须编写一个程序,其中main调用其他函数来测试一系列数字(如果有的话)是否小于一个数字,如果所有系列的数字都在两个限制之间,如果有的话是负数.我的代码返回值为1表示true,0表示false表示,但是赋值会将它们打印为"true"或"false".我不知道如何将bool答案从printf打印为字符串.我使用if(atl == false)printf("false"); 在我的at_least.c和main.c中,它只返回一个true或false的长字符串(例如:truetruetrue ....).我不确定这是不是正确的编码,我把它放在错误的位置,或者我需要使用其他一些代码.
这是我的main.c:
#include "my.h"
int main (void)
{
int x;
int count = 0;
int sum = 0;
double average = 0.0;
int largest = INT_MIN;
int smallest = INT_MAX;
bool atlst = false;
bool bet = true;
bool neg = false;
int end;
while ((end = scanf("%d",&x)) != EOF)
{
sumall(x, &sum); //calling function sumall
count++;
larger_smaller(x, &largest, &smallest); //calling function larger_smaller
if (atlst == false)
at_least(x, &atlst); //calling function at_least if x < 50
if (bet == true)
between(x, &bet); //calling function between if x is between 30 and 40 (inclusive)
if (neg == false)
negative(x, &neg); //calling function negative if x < 0
}
average = (double) sum / count;
print(count, sum, average, largest, smallest, atlst, bet, neg);
return;
}
Run Code Online (Sandbox Code Playgroud)
我对一组数字的结果:
The number of integers is: 15
The sum is : 3844
The average is : 256.27
The largest is : 987
The smallest is : -28
At least one is < 50 : 1 //This needs to be true
All between 30 and 40 : 0 //This needs to be false
At least one is negative : 1 //This needs to be true
Run Code Online (Sandbox Code Playgroud)
这是在C中,我似乎找不到多少.
在此先感谢您的帮助!
附录:
从下面的答案重复这一点.
这适用于at_least和negative函数,但不适用于between函数.我有
void between(int x, bool* bet)
{
if (x >= LOWER && x <= UPPER)
*bet = false;
return;
}
Run Code Online (Sandbox Code Playgroud)
作为我的代码.我不确定是什么问题.
R..*_*R.. 45
备用无分支版本:
"false\0true"+6*x
Run Code Online (Sandbox Code Playgroud)
Mit*_*eat 23
您可以使用C的条件(或三元)运算符:
(a > b) ? "True" : "False";
Run Code Online (Sandbox Code Playgroud)
或者在你的情况下:
x ? "True" : "False" ;
Run Code Online (Sandbox Code Playgroud)
Osc*_*orz 15
x ? "true" : "false"
上面的表达式返回一个char *,因此你可以这样使用:
puts(x ? "true" : "false");
要么
printf(" ... %s ... ", x ? "true" : "false");
你可能想为此制作一个宏.