C - 如何在 for 循环中只打印最大的数字? [英] C - How to print only the largest number in a for loop?

查看:78
本文介绍了C - 如何在 for 循环中只打印最大的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 Euler 项目的问题 4 - 从两个 3 位数字的乘积中找到最高的回文.我在网上找到了很多解决方案,但没有一个能解决我在使用自己的代码时遇到的问题.我不是一个有经验的编码员,刚刚开始休闲学习.

I am having a go at Project Euler question 4 - Finding the highest palindrome from a product of two 3-digit numbers. I have found many solutions online, none of which answer the issues I am experiencing with my own code. I am not an experienced coder and have just starter learning recreationally.

到目前为止,我的代码执行了一个 for 循环,它生成了所有回文数字.目前我打印所有这些只是为了检查它是否正常工作,它似乎是.我想知道是否有办法只打印循环中的最大数字?我不认为手动运行是最有效的方法.

My code so far does a for loop which generates all of the numbers that are palindromes. Currently I have it printing all of them just to check that it is working, which it appears to be. I was wondering if there was a way to print only the largest number in the loop? I don't think running through manually is the most efficient way of doing it.

这是目前的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main()
{
int a,b,c,d;

for(a=100;a<=999;a++){
    for(b=100;b<=999;b++){
        c=a*b;
        d=reverse(c);
        if(c==d){
            printf("%d is a palindrome\n",c);
        }
    }
}
return 0;
}

int reverse(int number){
    int answer=0;
    while(number!=0){
    int units=number%10;
    answer=answer*10+units;
    number=number/10;
}
return answer;
} 

推荐答案

将最大的结果分配给变量.然后当你发现另一个更大的变量时,更新那个变量.

Assign the largest result to a variable. Then when you find another that is bigger, update that variable.

然后当循环完成时,打印最大的变量的结果.

Then when the loop is complete, print the result from the variable which is the largest.

我会让你算出代码.这是微不足道的.

I'll let you work out the code. It's trivial.

这篇关于C - 如何在 for 循环中只打印最大的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆