我们如何在输出中打印最年轻的名字? 我想计算最年轻的人。
那是我的代码:
#include <stdio.h>
#include <conio.h>
int main() {
int john;
int ahmad;
int saleem;
printf("Enter the age of john,ahamd, saleem simaltanoeusly\n");
scanf_s("%d\n%d\n%d", &john, &ahmad, &saleem);
int youngest = john;
if (john > ahmad)
youngest = ahmad;
if (ahmad > saleem)
youngest = saleem;
printf("youngest of you is %d", youngest);
_getch();
return 0;
}
答案 0 :(得分:5)
你可以这样做,用宏
#include <stdio.h>
#define SHOW(varname) printf("%s is age %d", #varname, varname)
int main(void){
int john = 23;
int ahmed = 19;
int saleem = 27;
if (john < ahmed && john < saleem)
SHOW(john);
else if (ahmed < saleem)
SHOW(ahmed);
else
SHOW(saleem);
return 0;
}
节目输出:
ahmed is age 19
答案 1 :(得分:2)
最好将名称放在数组中。然后按索引引用每个名称。
const char * names[] = {
"John",
"Ahmad",
"Salem",
};
int youngestage = -1;
char* youngest = 0;
printf("Enter the age of john,ahamd, saleem simaltanoeusly\n");
for (int i=0;i<sizeof(names)/sizeof(names[0]);i++)
{
int age;
scanf("%d", &age);
if (youngestage == -1 || age < youngestage)
{
youngestage = age;
youngest = names[i];
}
}
printf("%s is the youngest", youngest);
printf("youngest of you is %d", youngestage);
答案 2 :(得分:0)
最简单的解决方案是为每个人创建一个结构,其中包含他们的名字和年龄。
struct person {
char *name;
int age;
}
您还需要确定最年轻的年龄。在你的情况下,你可以这样做:
int youngest = john;
if (youngest.age > ahmad.age)
youngest = ahmad;
if (youngest.age > saleem.age)
youngest = saleem;
对于通用解决方案,您应该通过循环遍历数组来完成此操作。
答案 3 :(得分:0)
所以你想在这里打印与最小值相关联的变量名吗?
预处理程序指令#与宏中的变量一起使用时输出编码器使用的变量名称
//Code by Rahul Anand Jha
//using GCC Compiler
#include <stdio.h>
#include <conio.h>
#define display(n) printf(#n) //add this
int main() {
int john;
int ahmad;
int saleem;
printf("Enter the age of john,ahamd, saleem simaltanoeusly\n");
scanf("%d\n%d\n%d", &john, &ahmad, &saleem);
if(john<ahmad && john <saleem)
display(john);
else if(ahmad<john && ahmad<saleem)
display(ahmad);
else
display(saleem);
return 0;
}
但是我建议你不要使用这样的解决方案,因为只有当你正在测试它们的人的名字是John,Ahmad,Saleem时,这才是有益的。否则你每次都需要修改你的代码。
您也可以使用Structures,Arrays。