Home > Backend Development > PHP Tutorial > 一个小小的算法有关问题

一个小小的算法有关问题

WBOY
Release: 2016-06-13 12:17:37
Original
877 people have browsed it

一个小小的算法问题
比如:我们充值话费的时候,充大于10元送1元话费,充大于50元送5元话费。

那么此时,我充值的是51元话费,我怎么去命中的是50元送5元话费,而此时不再命中大于10元送1元话费了。

老大,帮我看下吧

<br />$a = array('50'=>'5','10'=>'1');<br />$s = 51;<br />function test($s,$a){<br />	$flag = 0;<br />	foreach($a as $k=>$v){<br />		if($s >=$k){<br />			$flag=$v;<br />		}<br />	}<br />	return $flag;<br />}<br />echo test($s,$a);<br />
Copy after login

------解决思路----------------------
$a = array('50'=>'5','10'=>'1');<br />$s = 51;<br />function test($s,$a){<br />    $flag = 0;<br />    foreach($a as $k=>$v){<br />        if($s >=$k){<br />            $flag=$v;<br />            break; //这样比较规范(一个模块只有一个出口)<br />        }<br />    }<br />    return $flag;<br />}<br />echo test($s,$a);
Copy after login

------解决思路----------------------
引用:
如果$a 换成 $a = array('40'=>'3','50'=>'5','10'=>'1');
那么结果就是3了,这个时候51比50要大,应该是5啊


<br />[code=php]$a = array('50'=>'5','10'=>'1');<br />$s = 51;<br />function test($s,$a){<br />    $flag = 0;<br />    foreach($a as $k=>$v){<br />        if($s >=$k){<br />if($flag<$v)           <br /> $flag=$v;<br />           <br />        }<br />    }<br />    return $flag;<br />}<br />echo test($s,$a);
Copy after login

[/code]

数组是排列不规则的话就这样

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template